【发布时间】:2014-02-28 04:16:55
【问题描述】:
我通过实体AppointmentRequest 在Doctor 和Patient 之间建立了多对多关系。但是,当我删除 1 个 Doctor 时,每个通过 AppointmentRequest 表关联的 Doctor 和 Patient 都会被删除。
这是我的代码:
医生
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;
}
}
约会请求
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。这将删除所有相关的内容。就像一个涟漪效应,如果删除了父项,所有的子子项都会被删除。
-
您的多对多映射有误。请看这个mkyong.com/hibernate/…
-
为什么多对多映射错误。它工作得很好,我昨晚实际上实现了这个解决方案,它和我的解决方案做同样的事情。你能告诉我那个解决方案与我的相比有什么好处吗?另外,你是对的,级联不应该设置为全部。
-
我昨晚真的评论了那篇文章。我想知道使用该解决方案与这个解决方案相比的好处。
标签: java eclipse hibernate jpa