【问题标题】:How do I map this relationship using JPA/Hibernate?如何使用 JPA/Hibernate 映射这种关系?
【发布时间】:2018-11-24 10:04:36
【问题描述】:

我有两个共享一个公共键的表。我想要的是,当我为第一个表加载类时,我还会获得与第二个表对应的类列表,它们共享密钥。

更具体地说:tableA 的 id (id1) 存在于 tableB 的多个条目中。但是,tableB 使用复合键,并使用 id1 和 id2 作为键。

我想要实现的是,当表 A 的 POJO 被加载时,我还得到表 B 的所有条目,其中表 A 中的 id1 等于表 B 中的 id1。类似于:

public class TableA {
  private String id1;
  private List<TableB> list; // where id1 in tableA == id1 in tableB
}


table A id column: 
id1

table B composite id: 
id1 // same as for tableA
id2

【问题讨论】:

    标签: sql hibernate jpa hibernate-mapping


    【解决方案1】:

    B 类将有一个部分依赖于 A 的复合标识符。这可以使用 EmbeddedID 或通过指定 ID 类来映射。使用 ID 类如下所示:

    实体 A

    @Entity
    public class A {
        @Id
        @Column(name = "id1")
        private Long id1;
    
        @OneToMany(mappedBy = "a")
        private Set<B> bs;
    }
    

    实体 B

    @Entity
    @IdClass(Bid.class)
    public class B {
        @Id
        @ManyToOne
        @JoinColumn(name = "id1")
        private A a;
    
        @Id
        @Column(name = "id1")
        private Long id2;
    }
    

    B 的 ID 类

    public class Bid implements Serializable{
        //must be of same type as id of target entity A
        private Long a;
        private Long id2;
    
        // **must** implement equals and hash code
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多