Java 使用复合键持久化元素列表

Java 使用复合键持久化元素列表,java,jpa,persistence,seam,Java,Jpa,Persistence,Seam,我使用java持久性来保存与另一个实体关联的实体列表。下面是我遇到一些问题的简要说明 @Entity public class Offer implements Serializable { @Id private Long offerId; @OneToMany @Column List<OfferCategory> offerCategories; } @Entity public class OfferCategory implements Serializab

我使用java持久性来保存与另一个实体关联的实体列表。下面是我遇到一些问题的简要说明

@Entity public class Offer implements Serializable {
  @Id private Long offerId;

  @OneToMany
  @Column List<OfferCategory> offerCategories;
}

@Entity public class OfferCategory implements Serializable {

  @Embeddable public static class Id implements Serializable
  {
      @Column(name="offer_id")
      private Long offerId;

      @Column(name="category_id")
      private Long categoryId;

      public Id() {}

      public Id(Long offerId, Long categoryId) {
          this.offerId = offerId;
          this.categoryId = categoryId;
      }

      public boolean equals(Object o) {
          if(o != null && o instanceof Id) {
              Id other = (Id) o;
              return this.offerId.equals(other.offerId) &&
                      this.categoryId.equals(other.categoryId);
          }
          else
              return false;
      }

      public int hashCode() {
          return offerId.hashCode() + categoryId.hashCode();
      }
  }
  @EmbeddedId private Id id = new Id();
}
@Entity公共类提供实现了可序列化{
@Id私人长offerId;
@独身癖
@分类的列列表;
}
@实体公共类OfferCategory实现可序列化{
@可嵌入的公共静态类Id实现了可序列化
{
@列(name=“offer\u id”)
私人长offerId;
@列(name=“category\u id”)
私人长类别;
公共Id(){}
公共Id(长offerId,长categoryId){
this.offerId=offerId;
this.categoryId=categoryId;
}
公共布尔等于(对象o){
if(o!=null&&o instanceof Id){
Id其他=(Id)o;
返回this.offerId.equals(other.offerId)&&
此.categoryId.等于(其他.categoryId);
}
其他的
返回false;
}
公共int hashCode(){
返回offerId.hashCode()+categoryId.hashCode();
}
}
@EmbeddedId私有Id=新Id();
}
本质上,由于我无法更改架构,我需要将类别列表保存为分配给报价

现在,我从用户那里得到一个类别列表,然后将它们放入Offer的offerCategories字段中。但是,这不适用于新产品,因为我无法设置新产品的ID


我不熟悉JPA和Seam,因此如果有人能给我一个正确的方向,我将不胜感激。

我以前没有尝试过使用复合ID,但需要注意的是@Column仅用于更改字段使用的数据库列的属性。它没有规定一种关系,所以你仍然需要这样的东西:

@OneToMany    
List<OfferCategory> offerCategories;
@OneToMany
分类清单;

当我查看教程时,我发现:

不能使用IdentifierGenerator生成复合键。相反,应用程序必须分配自己的标识符

所以你必须自己分配id。也许您可以创建一个DB序列并使用本机查询获取其值?

还有一句话——如果您想使用列表映射(报价中类别的顺序由数据库定义),您需要一个索引列来包含列表中的索引。如果类别的顺序不重要,那么设置会更方便。

好吧,我现在的解决方案是,我保留每一个类别(为新条目创建键),然后将它们填充到列表中,然后将它们填充到容器对象中,然后保留该对象。

但是如果它们都是Offer的子对象,我会为它们分配一个类别,难道它不能在分配新id的同时填写id吗?