在hibernate中以多对一关系删除记录是行不通的

时间:2014-03-19 09:27:29

标签: hibernate

reports.hbm.xml

    <hibernate-mapping>
       <class name="com.srdiagnostic.app.bdo.Reports" table="REPORTS" schema="SR">
    <id name="reportsId" type="long">
        <column name="REPORTS_ID" precision="22" scale="0" />
        <generator class="increment"/>
    </id>
    <property name="reportDate" type="date">
        <column name="REPORT_DATE" length="7" />
    </property>
    <many-to-one name="patient" class="com.srdiagnostic.app.bdo.Patient" fetch="select" cascade="all" unique="true" lazy="false">
        <column name="PATIENT_ID" precision="22" scale="0" />
    </many-to-one>
    <many-to-one name="doctor" class="com.srdiagnostic.app.bdo.Doctor" fetch="select" cascade="all" unique="true" lazy="false">
        <column name="doctor_ID" precision="22" scale="0" />
    </many-to-one>

我能够一次在报告和医生表中正确插入记录,但无法一次删除报告和医生中的记录。删除报告表中的记录时,它仅在报告表中删除,但一次不在医生表中删除。

   Dao class
    public void deleteReport(Reports report) throws AppException, AppSysException {
    Session  session = SRHibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    session.delete(report);
    session.getTransaction().commit();
    System.out.println("Report deleted successfully");
   }
   Reports.java 
   public class Reports  implements java.io.Serializable {
   private Long reportsId;
   private Date reportDate;
   private Patient patient;
   private Doctor doctor;
    //setters&getters }
    Doctor.java
    public class Doctor  implements java.io.Serializable {
   private long doctorId;
   private String doctorName;
   private String place;    
   //setters&getters }

1 个答案:

答案 0 :(得分:2)

“它(仅)在报告表中删除,但一次不在Doctor表中删除。”

关系仅存在于多方面,即。该报告拥有引用相关医生的外键。删除报告时,您无需在医生表中删除任何内容。

事实是许多报告可能会引用医生,因此您不能在删除单个报告时触发医生删除。

如果您的目的是删除医生的报告(将其从医生的报告集中删除),删除孤儿将完成工作(orphanRemoval =在关系的OneToMany方面为真)