如何使用 JPA/Hibernate 映射此关系?
How do I map this relationship using JPA/Hibernate?
我有两个共享公用密钥的 table。我想要的是,当我为第一个 table 加载 class 时,我还会得到一个 classes 的列表,对应于他们共享的第二个 table钥匙。
更具体地说:tableA 有一个 ID (id1),它存在于 tableB 的多个条目中。但是,tableB使用复合键,同时使用id1和id2作为键。
我想要实现的是,当加载 tableA 的 POJO 时,我还获得了 tableB 的所有条目,其中来自 tableA 的 id1 等于 id1在 table B. 类似于:
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
Class B 将有一个部分依赖于 A 的复合标识符。这可以使用 EmbeddedID
或通过指定 ID class 进行映射。使用 ID class 将如下所示:
实体 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;
}
ID Class 为 B
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
}
我有两个共享公用密钥的 table。我想要的是,当我为第一个 table 加载 class 时,我还会得到一个 classes 的列表,对应于他们共享的第二个 table钥匙。
更具体地说:tableA 有一个 ID (id1),它存在于 tableB 的多个条目中。但是,tableB使用复合键,同时使用id1和id2作为键。
我想要实现的是,当加载 tableA 的 POJO 时,我还获得了 tableB 的所有条目,其中来自 tableA 的 id1 等于 id1在 table B. 类似于:
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
Class B 将有一个部分依赖于 A 的复合标识符。这可以使用 EmbeddedID
或通过指定 ID class 进行映射。使用 ID class 将如下所示:
实体 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;
}
ID Class 为 B
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
}