我正在使用Liquibase使用Spring Data JPA,我有两个类,第一个类具有简单键,第二个类具有复合键(多对多关系)
头等舱:
public class Person {
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "person_adress", joinColumns = { @JoinColumn(name = "person_id") }, inverseJoinColumns = {
@JoinColumn(name = "adress_id"), @JoinColumn(name = "country") })
private List<Adress> adresses;
// Other attributes
}
第二堂课:
public class Adress {
@EmbeddedId
private AdressId adressId; // contains adress_id and country as composite key
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "adresses")
private List<Person> persons;
// Other attributes
}
Liquibase文件:
<changeSet id="......." author="........">
<createTable tableName="person_adress">
<column name="person_id" type="varchar(255)">
<constraints nullable="false" />
</column>
<column name="adress_id" type="varchar(255)">
<constraints nullable="false" />
</column>
<column name="country" type="varchar(2)">
<constraints nullable="false" />
</column>
</createTable>
<addUniqueConstraint
columnNames="country, adress_id,person_id"
constraintName="keey"
tableName="person_adress" />
</changeSet>
当我致电此服务时:
adress.add(ListOfPersons);
adressRepository.save(adress);
在postgresql中,adress仍然存在并且也保留了人员列表,但是person_adress表仍然为空的问题
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以在以下链接中找到相同的方法(多列对多列)。
作者不是使用@ManyToMany,而是使用bidirecitional @OneToMany定义了一个额外的对象来表示带有和@EmbeddedId(PostTag和PostTagId)的相关对象