【发布时间】:2019-02-26 16:06:54
【问题描述】:
大家好,我确实有以下代码:
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class Doctor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "doctor_patient",
joinColumns = {@JoinColumn(name="doctor_id")},
inverseJoinColumns ={@JoinColumn(name="patient_id")})
private Set<Patient> patients = new HashSet<>();
//getters and setters
}
还有这个实体:
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class Patient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "patients")
private Set<Doctor> doctorList = new HashSet<>();
//Getters and setters
}
这是我正在做的使用 sn-ps 的测试:
@Test
@Transactional
public void testSaveDoctor(){
Doctor firstDoctor = new Doctor();
firstDoctor.setFirstName("test doc");
firstDoctor.setLastName("lname doc");
Patient firstPatient = new Patient();
firstPatient.setFirstName("patient 1");
firstPatient.setLastName("patient lname1");
firstDoctor.getPatients().add(firstPatient);
firstPatient.getDoctorList().add(firstDoctor);
rDoctor.save(firstDoctor);
}
我正在使用标准的 CRUD 存储库,结果是我在 Patient 和 Doctor 表中都有记录,但是表 doctor_patient 是空的,并且永远不会插入正确的数据。 如何解决?
【问题讨论】:
标签: java mysql spring hibernate orm