如何使用休眠 JPA 注释映射嵌套集合 Map<Key,List<Values>>? [英] How do I map a nested collection, Map&lt;Key,List&lt;Values&gt;&gt;, with hibernate JPA annotations?

查看:33
本文介绍了如何使用休眠 JPA 注释映射嵌套集合 Map<Key,List<Values>>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class I am not sure how to annotate properly.

我对 Holder::data 的目标:

My goal for Holder::data:

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

我也愿意接受另一种移除地图的设计,如果这能让设计更简洁.

I am also open to a different design that removes the map, if that would make for a cleaner design.

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

推荐答案

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

I don't think it is possible with hibernate(-core) to map any collection of collections:

集合可能包含几乎任何其他 Hibernate 类型,包括所有基本类型、自定义类型、组件、当然,参考其他实体.

Collections may contain almost any other Hibernate type, including all basic types, custom types, components, and of course, references to other entities.

(来自 官方文档)

注意几乎和集合类型的省略.

Notice the almost and the omission of the collection type.

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

A workaround: You need to introduce a new type 'in between' the collection holder and the element. This type you can map as an entity or a component and it refers the original content of the map, in this case a list.

类似于:

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

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

The rest of the mapping depends on your particular situation, but is rather straightforward.

这篇关于如何使用休眠 JPA 注释映射嵌套集合 Map<Key,List<Values>>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆