2014-02-28 73 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