【问题标题】:How to have 2 collections of the same type in JPA?如何在 JPA 中拥有 2 个相同类型的集合?
【发布时间】:2010-10-14 18:22:11
【问题描述】:

我在 JPA 中有 2 个实体:Entry 和 Comment。条目包含两个 Comment 对象的集合。

@Entity
public class Entry {
    ...

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @IndexColumn(base = 1, name = "dnr")
    private List<Comment> descriptionComments = new ArrayList<Comment>();

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @IndexColumn(base = 1, name = "pmnr")
    private List<Comment> postMortemComments = new ArrayList<Comment>();

    ...
}

为了存储这些对象,JPA+Hibernate 创建了“Entry”表、“Comment”表和 SINGLE“Entry_Comment”:

create table Entry_Comment (Entry_id integer not null, postMortemComments_id integer not null, pmnr integer not null, descriptionComments_id integer not null, dnr integer not null, primary key (Entry_id, dnr), unique (descriptionComments_id), unique (postMortemComments_id))

对象存储失败,因为descriptionComments_idpostMortemComments_id 不能同时为“非空”。

如何使用 JPA+Hibernate 存储包含两个相同类型集合的对象?

【问题讨论】:

    标签: java hibernate jpa collections persistence


    【解决方案1】:

    这是众多 Hibernate 错误之一(准确地说是HHH-3410)。

    我设法通过将@JoinTable 注释添加到@OneToMany 关系来修复它,每个关系都有自己的表名。

    在你的情况下,它看起来像这样:

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name="entity_descriptioncomments")
    @IndexColumn(base = 1, name = "dnr")
    private List<Comment> descriptionComments = new ArrayList<Comment>();
    
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name="entity_postmortemcomments")
    @IndexColumn(base = 1, name = "pmnr")
    private List<Comment> postMortemComments = new ArrayList<Comment>();
    

    注意:您还必须添加 @IndexColumn 注释(因为多个 EAGER 包的另一个 Hibernate 问题:HHH-1718/EJB-346)。

    【讨论】:

    • 你如何使这种关系成为双向的?
    【解决方案2】:

    要使用 DataNucleus (http://www.datanucleus.org) 在 JPA 中存储 2 个类似的集合,您将完全按照您所做的那样做。您没有 @JoinTable 注释,因此每个集合都应在 Comment 中放置一个 FK。如果您确实在某处有 @JoinTable(或 XML 等效项),那么设置相应连接表的名称(每个集合一个)也可以(因此它们有自己的连接表)。在 DataNucleus 中也可以在 2 个集合之间共享连接表,但这不是标准 JPA,而是供应商扩展。

    我不知道它如何映射到 Hibernate,但这是 JPA,所以应该保持一致,因为这就是拥有规范的重点;-)

    【讨论】:

      【解决方案3】:

      从数据模型/域模型的角度来看,当前映射存在缺陷:您实际上在 Entry 之间存在 single @OneToMany 关系> 和评论。并且 Comment 实体应该还有一个名为 type 的属性,它需要 2 个值:'description' 或 'postMortem' .

      为了与您当前的 Entry 实体实现内联,您可能需要考虑将 Comment 实体分解为 2 个不同的实体(可能使用 JPA 继承功能)并使用 Entry 中的 em>@JoinTable 注释。

      【讨论】:

        【解决方案4】:

        如果您只关心排序,那么如何将两个索引列定义配置为具有相同的名称?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多