【问题标题】:Defining relationship attributes in JPA在 JPA 中定义关系属性
【发布时间】:2014-12-19 05:55:49
【问题描述】:

我有一个OneToMany 关系定义如下

class ActionSet {
    @OneToMany
    List<Action> action;
}
class Action {
    ActionSet actionSet;
    Boolean isShared;
}

动作可以在多个动作集之间共享,也可以与单个动作集相关联。

当一个动作被共享时,它可能对某些动作集很重要,但对另一些则不重要。这里isImportant 是一个关系属性。如何在 JPA 中定义这种关系?

【问题讨论】:

    标签: java hibernate jpa spring-data-jpa


    【解决方案1】:

    基本上你需要如下三个实体类:

    动作集:

    @Entity
    public class ActionSet {
    
        @OneToMany(mappedBy = "actionSet")
        List<ActionSetAction> action;
    }
    

    行动:

    @Entity
    public class Action {
    
        @OneToMany(mappedBy = "action")
        List<ActionSetAction> action;
    }
    

    ActionSetAction(代表Join表):

    @Entity
    public class ActionSetAction {
    
        @ManyToOne
        @JoinColumn(name = "action_set_id")
        private ActionSet actionSet;
    
        @ManyToOne
        @JoinColumn(name = "action_id"
        private Action action;
    
        @Column(name ="is_important"
        private boolean important;
    }
    

    如果您想在数据库级别而不是内存中区分重要和不重要的操作集操作,那么您可以查看使用非 JPA Hibernate 特定的 @Where 注释。

    @Entity
    public class ActionSet {
    
        @OneToMany(mappedBy = "action")
        @Where(clause="is_important = true")
        List<ActionSetAction> importantActions;
    
        @OneToMany(mappedBy = "action")
        @Where("is_important = false")
        List<ActionSetAction> unimportantActions;
    }
    

    请注意,我最近回答了一个问题,在该问题中我建议使用纯 JPA 解决方案来解决非常相似的问题。然而,虽然这在 EclipseLink 中有效,但在 Hibernate 中存在问题。

    JPA ManyToMany where annotation

    【讨论】:

    • 感谢您的详细回答。我的搜索最终得到了相同的结果。我唯一担心的是它会产生 4 个以上的数据库表,而不是当前的 3 个
    • 我不明白为什么您需要 4 个表而不是 3 个。无论如何,您应该将其标记为正确答案。
    猜你喜欢
    • 2016-05-20
    • 2017-04-02
    • 1970-01-01
    • 2015-08-08
    • 2012-08-15
    • 1970-01-01
    • 2020-01-28
    • 2010-09-18
    • 2017-07-07
    相关资源
    最近更新 更多