Hibernate:删除整个表的多对多删除

时间:2014-02-28 04:16:55

标签: java eclipse hibernate jpa

Doctor&amp;之间有一个ManyToMany关系Patient通过实体AppointmentRequest。但是,当我每DoctorDoctor删除1 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;
   }

}

病人

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;
   }
}

AppointmentRequest

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();
    }
}

医生删除代码

{{1}}

1 个答案:

答案 0 :(得分:0)

在与连接表的ManyToMany关系中,连接表的存在仅用于创建关系。当关系被破坏/删除时Hibernate 将自动更新/删除表中与该关系对应的行条目。连接表没有等效的实体定义。换一种说法 连接表中的行本身不代表实体。它没有身份,也不能被其他实体共享/引用。但是在你的情况下,你建模的方式就是这样 您创建了一个可共享/可引用的单独实体AppointmentRequest并封装了该关系。这种设计通常在除了两个相关实体之外完成时,你有一些其他属性可以存储,例如创建日期,由等等创建。然后,您可以要求实体告知何时创建此关系或由谁创建。因此,您需要问的问题是,您是否只想要many-to-many关系,或者您的关系本身就是一个实体。