我有一個ManyToMany關係Doctor
& Patient
通過一個實體AppointmentRequest
。但是,當我刪除Doctor
每Doctor
& Patient
關聯通過AppointmentRequest
表被刪除。休眠:多對多刪除刪除整個表
這裏是我的代碼:
醫生
public class Doctor implements Person {
private List<AppointmentRequest> appointmentRequests = new ArrayList<AppointmentRequest>();
@OneToMany(mappedBy="doctor", targetEntity = AppointmentRequest.class,
fetch=FetchType.EAGER, cascade= CascadeType.ALL)
public List<AppointmentRequest> getAppointmentRequests() {
return this.appointmentRequests;
}
}
患者
public class Patient implements Person {
private List<AppointmentRequest> appointmentRequests = new ArrayList<AppointmentRequest>();
@OneToMany(mappedBy="patient", targetEntity = AppointmentRequest.class,
fetch=FetchType.EAGER, cascade= CascadeType.ALL)
public List<AppointmentRequest> getAppointmentRequests() {
return this.appointmentRequests;
}
}
AppointmentRequest
public class AppointmentRequest {
private Doctor doctor;
private Patient patient;
@ManyToOne (fetch = FetchType.EAGER, cascade= CascadeType.ALL)
@JoinColumn(name="doctor_id")
public Doctor getDoctor() {
return doctor;
}
@ManyToOne (fetch = FetchType.EAGER, cascade= CascadeType.ALL)
@JoinColumn(name="patient_id")
public Patient getPatient() {
return patient;
}
}
醫生刪除代碼
public void deleteDoctor(String doctor_name) {
Session session = sessionFactory.openSession();
Doctor doctor = new Doctor();
try {
session.beginTransaction();
Query query = session.getNamedQuery("Doctor.findByName");
query.setString("name", doctor_name);
doctor = (Doctor) query.uniqueResult();
if(doctor == null) {
throw new NullPointerException();
}
List<AppointmentRequest> appointments = doctor.getAppointmentRequests();
for(AppointmentRequest appointment:appointments) {
appointment.setDoctor(null);
}
session.delete(doctor);
session.getTransaction().commit();
}
finally {
session.close();
}
}
您在集合上設置了cascade.all。這將刪除所有相關的內容。這是一種漣漪效應,如果父母被刪除,所有的子孩子都會被刪除。 – Zeus
你有許多不合理的映射錯誤。請看這個http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/ – Zeus
爲什麼多對多映射不對。它的工作原理非常完美,我昨天晚上實施了這個解決方案,它和我的解決方案完全相同。你能告訴我這個解決方案與我的好處嗎?此外,你是正確的,級聯應該沒有被設置爲全部。 – user2158382