如何使用hibernate JPA注释映射嵌套集合Map <Key,List <Values >>?

Nat*_*ger 15 java collections annotations hibernate jpa

我有一节课,我不确定如何正确注释.

我对Holder :: data的目标:

  • 列表应该不是通过比较器而是通过数组中元素的自然顺序来维护顺序.(如果有帮助,可以是ndx列.)
  • 持有人将拥有唯一的数据参考,因此Cascade all也可能适用.

我也愿意采用不同的设计来移除地图,如果这样可以实现更清洁的设计.

@Entity
public class Holder extends DomainObject {
  private Map<Enum,List<Element>> data;
}

@Entity
public class Element extends DomainObject {
  private long valueId;
  private int otherData;
}

@Mappedsuperclass
public class DomainObject {
 // provides id
 // optimistic locking
 // create and update date
}
Run Code Online (Sandbox Code Playgroud)

Maa*_*els 9

我不认为用hibernate(-core)映射任何集合集合是可能的:

集合可能包含几乎任何其他Hibernate类型,包括所有基本类型,自定义类型,组件,当然还有对其他实体的引用.

(来自官方文件)

注意集合类型的几乎和遗漏.

解决方法:您需要在集合持有者和元素之间引入一个新类型.您可以将此类型映射为实体或组件,它引用地图的原始内容,在本例中为列表.

就像是:

@Entity
public class Holder extends DomainObject {
  @OneToMany
  private Map<Enum,InBetween> inBetweens;
}

@Entity
public class InBetween extends DomainObject {
  @OneToMany
  private List<Element> elements;
}

@Entity
public class Element extends DomainObject {
  private long valueId;
  private int otherData;
}

@Mappedsuperclass
public class DomainObject {
 // provides id
 // optimistic locking
 // create and update date
}
Run Code Online (Sandbox Code Playgroud)

映射的其余部分取决于您的特定情况,但相当简单.