我使用spring jpa数据。在多对多的关系中,我想保存一个关联。
@Entity
public class Lodger {
...
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY, mappedBy = "lodger")
private List<MedicalContact> medicalContactList;
}
@Entity
public class MedicalContact {
...
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinColumn(name = "lodger_id")
private List<Lodger>lodger;
}
我的方法相互关联。
public void associateLodgerAndMedicalContact(Long lodgerId, Long medicalContactId){
Lodger lodger = lodgerRepository.findOne(lodgerId);
List<MedicalContact> medicalContactList = lodger.getMedicalContactList();
if(medicalContactList==null){
medicalContactList = new ArrayList<>();
}
MedicalContact medicalContact = medicalContactRepository.findOne(medicalContactId);
medicalContactList.add(medicalContact);
List<Lodger> lodgerList = medicalContact.getLodger();
if(lodgerList==null){
lodgerList = new ArrayList<>();
}
lodgerList.add(lodger);
lodgerRepository.save(lodger)
medicalContactRepository.save(medicalContact);
}
我是否需要添加双方的每个对象?
答案 0 :(得分:0)
不,你不必双方都做,一方应该做。
您需要JoinTable
ManyToMany
关系而不是JoinColumn
我建议您在Entity类上创建add方法,这样每次想要添加新元素时都不必重复它:
@Entity
public class Lodger {
...
@ManyToMany( mappedBy = "lodger")
@JoinTable(name="yourTableName",joinColumns=@JoinColumn("LODGER_ID") , reverseJoinColumn=@JoinColumn(name="MEDICAL_CONTACT_ID"))
private List<MedicalContact> medicalContactList;
public void addToMediaContactList(MedicalContact medicalContact){
if(medicalContact == null){
//return; or throw new IllegalArgumentException("MedicalContact can't be null)" or any Other Exception ....
}
if(medicalContactList == null){
this.medicalContactList = new ArrayList<>();
}
medicalContactList.add(medicalContact);
}
}
关于你的关联方法:
public void associateLodgerAndMedicalContact(Long lodgerId, Long medicalContactId){
Lodger lodger = lodgerRepository.findOne(lodgerId);
MedicalContact medicalContact = medicalContactRepository.findOne(medicalContactId);
lodger.addToMedicalContactList(medicalContact );
lodgerRepository.save(lodger)
}