2014-02-28 75 views
0

我有一个ManyToMany关系Doctor & Patient通过一个实体AppointmentRequest。但是,当我删除DoctorDoctor & 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(); 
    } 
} 
+0

您在集合上设置了cascade.all。这将删除所有相关的内容。这是一种涟漪效应,如果父母被删除,所有的子孩子都会被删除。 – Zeus

+0

你有许多不合理的映射错误。请看这个http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/ – Zeus

+0

为什么多对多映射不对。它的工作原理非常完美,我昨天晚上实施了这个解决方案,它和我的解决方案完全相同。你能告诉我这个解决方案与我的好处吗?此外,你是正确的,级联应该没有被设置为全部。 – user2158382

回答

0

与联结表中的ManyToMany关系,连接表的存在只是为了创建关系。当关系被破坏/删除时,Hibernate 会自动更新/删除表中与该关系相对应的行条目。连接表没有等价的实体定义。换句话说, 连接表中的行不表示实体本身。它没有身份,不能被其他实体共享/引用。然而在你的情况下,你建模的方式是 你已经创建了一个单独的实体AppointmentRequest,它是可共享/可引用的并封装了关系。这种设计通常是在除了两个相关的实体之外完成的,您可以使用其他属性来存储例如创建日期,等等。然后,您可以要求实体告知何时创建了该关系或由谁创建。所以你需要问的问题是你是想要一个many-to-many关系还是你的关系是一个实体。

+0

是的,我的JOIN表是一个实体的特定需求。我在那里存储了我在示例代码中遗漏的其他属性。我想我应该分享我的问题所需的具体细节 – user2158382