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

问题描述 投票:0回答:3

我有一堂课,我不知道如何正确注释。

我对 Holder::data 的目标:

  • List 不应该通过比较器来维持顺序,而是通过数组中元素的自然顺序来维持顺序。 (如果有帮助的话,这可以是一个 ndx 列。)
  • Holder 将拥有对数据的唯一引用,因此 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
}
java hibernate collections jpa annotations
3个回答
10
投票

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

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

(来自官方文档

注意 almost 和集合类型的省略。

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

类似:

@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
}

映射的其余部分取决于您的具体情况,但相当简单。


3
投票

这是一个关于hibernate中集合集合的博客https://xebia.com/blog/mapping-multimaps-with-hibernate/

希望能有所帮助。它帮助了我。

问候, 安东


-1
投票

请注意,引用的 Hibernate 文档链接似乎已过时,我发现以下工作有效:http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html

© www.soinside.com 2019 - 2024. All rights reserved.