我有一个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