spring data jpa配置一对多和多对一
程序员文章站
2022-04-23 23:43:27
...
使用注解的形式配置多表关系:
1、声明关系:
@OneToMany(一对多):
@ManyToOne(多对一):
targetEntity(对方对象的字节码对象)
2、配置外键:
@JoinColumn:配置外键
name:外键字段名称
referencedColumnName:参照的主表的主键字段名称
配置客户与联系人之间的关系(一对多):
Customer.java:
// 配置客户与联系人的关系(一对多)
@OneToMany(targetEntity = Contactor.class)
@JoinColumn(name = "contact_id", referencedColumnName = "cust_id")
private Set<Contactor> contactors = new HashSet<>();
配置联系人与客户的关系(多对一):
Contactor.java:
@ManyToOne(targetEntity = Customer.class)
@JoinColumn(name = "contact_id", referencedColumnName = "cust_id")
private Customer customer;