我有 2 张 table :
表A
id(PK) name
------------
1 aa
2 ab
3 ac
4 ad
表B
master_id(FK_id) slave_id(FK_id)
1 2
2 3
2 4
表 A 和表 B 具有一对多关系。 表 B 具有 2 列(master_id、slave_id)的复合键,如上所示。并且B表中的两列都与A表有外键关系。
我们如何使用 spring JPA/hibernate 处理这个实体映射?
最佳答案
A 表的映射非常简单:
@Entity
public class A {
@Id
private Long id;
private String name;
// setters, getters, etc
}
对于 B 表,您必须声明多对一关系和复合 id。使用 @EmbeddedId
时,您不能将实体引用用作字段,因此在这种情况下 @IdClass
似乎更好:
@Entity
@IdClass(BId.class)
public class B {
@Id
@ManyToOne
private A master;
@Id
@ManyToOne
private A slave;
// setters, getters, etc
}
最后一个,BId.class。同样,您不能使用实体引用作为字段,但可以用 A.id 类型(长整型)替换它们:
public class BId implements Serializable {
private Long master;
private Long slave;
}
关于spring - JPA : How to handle the entity mapping with two foreign keys and those two foreign together acts as a primary key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695741/