2012-11-10 124 views
0

我正在使用HIbernate 3.2.5。我有部門和培訓表之間的一對多關聯。一個部門有能力參加一次以上的培訓。Cascade DELETE關聯混淆

<id name="deptId" type="integer" column="DEPT_ID"> 
     <generator class="assigned"></generator> 
    </id> 
    <property name="deptName"> 
     <column name="DEPT_NAME"></column> 
    </property> 
    <map name="trainingDetails" inverse="false" cascade="delete" lazy="false"> 
     <key column="DEPT_ID"></key> 
     <map-key formula="ID" type="integer"></map-key> 
     <one-to-many class="model.Training"/> 
    </map>  

當我嘗試刪除條目:

SessionFactory sf = new Configuration().configure("trial.cfg.xml").buildSessionFactory(); 
    Session session = sf.openSession(); 
    Dept department = new Dept(); 
    department.setDeptId(2);   
    session.delete(department); 
    session.flush(); 
    session.close(); 

我可以看到,子表更新查詢是越來越打印在控制檯,而不是刪除查詢:

update training set DEPT_ID=null where DEPT_ID=? 

但是因爲級聯是delete因此子表也應該執行delete操作而不是update對不對?

請讓我知道我的錯誤在哪裏。

問候,

回答

1

如果使用級聯爲DELETE_ORPHAN指出,子對象不能獨立存在,它會做。

另外,您在刪除之前沒有加載對象圖。執行刪除如下:

SessionFactory sf = new Configuration().configure("trial.cfg.xml") 
             .buildSessionFactory(); 
    Session session = sf.openSession(); 
    //load the object before deleting 
    Dept department = session.get(Dept.class, new Integer(2)); 
    session.delete(department); 
    session.flush(); 
    session.close(); 
+0

不,我試過但得到了同樣的結果。仍然執行'update'而不是子表上的'delete'。 – user182944

+0

@ user182944更新了答案。請嘗試。 –

+0

現在確定'delete'和'delete-orphan'正在工作。是因爲我加載對象的方式嗎?請詳細解釋一下。 – user182944