【问题标题】:Additional "outer" join columns on a JPA entity relationship through a join table通过连接表在 JPA 实体关系上附加“外部”连接列
【发布时间】:2019-12-23 21:07:27
【问题描述】:

我有两个通过连接表关联的实体,使用 JPA 建模,如下所示:

class EntityA {

  @ManyToMany
  @JoinTable(name="joining_entity",
    joinColumns={@JoinColumn(name="entity_a_id", referencedColumnName="id")},
    inverseJoinColumns={@JoinColumn(name="entity_b_id", referencedColumnName="id")}
  )
  List<EntityB> entityBList;

  Long importantIdentifier;

}

class EntityB {

  @ManyToMany(mappedBy="entityBList")
  List<EntityA> entityAList;

  Long importantIdentifier;

}

这适用于简单的多对多关系,但在我的情况下,我还需要仅在 importantIdentifier 在两个实体中匹配时才加入。

对于临时查询,只需将ON 子句添加到连接中即可:AND entity_a.important_identifier=entity_b.important_identifier

但是,我正在努力使用 JPA/Hibernate 注释对此进行建模。我试过了:

  • 添加一个额外的 @JoinColumn@JoinTable -- 这将被忽略
  • 添加 @Where@WhereJoinTable 注释 -- 不幸的是,似乎没有办法引用外部表/实体,只有连接表

如果有其他方法可以实现这一点,我不喜欢使用@JoinTable,即使用表示连接表的第三个具体实体的某种方法。

【问题讨论】:

    标签: hibernate jpa


    【解决方案1】:

    此建模将为您提供所需的灵活性。为名为relationalAB 的第三个实体建模,并将模型EntityA 和EntityB 从@ManyToMany 更改为@OneToMany。在您的新关系AB 模型中,我将为EntityA 和EntityB 提供两个@ManytoOne 映射:` 示例:

    @Entity
    @Table(name = "RELATIONAL_A_B")
    public class relationalAB {
    
        @Id
        @GeneratedValue
        @Column(name="RELATIONAL_A_B_ID")
        protected Integer id;
    
    
        @ManyToOne(fetch=FetchType.LAZY)
        @JoinColumn(name = "enitityA_id", insertable = false, updatable = false)
        protected EntityA entityA;
    
        @ManyToOne(fetch=FetchType.LAZY)
        @JoinColumn(name = "enitityB_id", insertable = false, updatable = false)
        protected EntityB entityB;
        ...
    
    @Entity
    @Table(name = "ENTITY_A")
    public class EntityA {
    
        @Id
        @GeneratedValue
        @Column(name="ENTITY_A_ID")
        protected Integer id;
    
    
        @OneToMany(mappedBy = "entityA", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}, fetch = FetchType.LAZY)
        List<relationalAB> weakEnityList;
    
        ...
    
    @Entity
    @Table(name = "ENTITY_B")
    public class EntityB {
    
        @Id
        @GeneratedValue
        @Column(name="ENTITY_B_ID")
        protected Integer id;
    
        @OneToMany(mappedBy = "entityB", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}, fetch = FetchType.LAZY)
        List<relationalAB> weakEnityList;
    
        ...`
    

    【讨论】:

    • 我了解如何映射连接实体,问题的关键在于能够使用另一对列来进一步限制直接从 A 到 B 的连接(在我的示例中为 importantIdentifier)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多