2011-01-28 27 views
1

版本:3.6.0.final休眠不插入重新附加的集合? (錯誤?)

我有以下情況: 一個具有收藏單位,包含值類型的對象,使用層疊完全啓用。

1)我刪除,收集並將其存儲到數據庫。然後加載它來檢查集合是否確實被刪除。 2)然後我添加刪除的集合並再次存儲實體。然後我再次加載它來檢查結果,並注意到該集合是空的,它不應該:(... 我做錯了什麼或這是一個錯誤? 當我在2中使用一個乾淨的創建集合) ,它不存在Hibernate對象,它工作正常..,即:集合正確存儲在數據庫中。

在代碼中,我的映射:

<class name="com.sample.Declaration" table="decl"> 
<id name="id" column="id" type="string" length="40" access="property"> 
    <generator class="assigned" /> 
</id> 
<set name="statusHistory" table="decl_sts_hist" lazy="false" cascade="all"> 
    <cache usage="read-write" /> 
    <key column="idDec" not-null="true" /> 
    <composite-element class="com.sample.DeclarationStatusDefault"> 
    <property name="remark" column="remark" type="string" length="254" /> 
    <property name="statusName" column="stsName" type="declarationStatusName" not-null="true" update="false" /> 
    </composite-element> 
</set> 
</class> 

代碼:

// 1): clear the status history 
Declaration dec = Persister.findDeclarationById("id"); 
SortedSet<DeclarationStatus> history = dec.getStatusHistory(); 
dec.setStatusHistory(null); 
dec.saveOrUpdate(); // will call saveOrUpdate on the current session. 

Declaration dec = Persister.findDeclarationById("id"); 
assertNull(dec.getStatusHistory()); // OK 

// 2) recover the status history 
dec.setStatusHistory(history); 
dec.saveOrUpdate(); // will call saveOrUpdate on the current session. 

Declaration dec = Persister.findDeclarationById("id"); 
assertNotNull(dec.getStatusHistory()); // ERROR, is empty like before 

如果我創建了一套新的有幾個條目和存儲,這一切工作正常,但是當我保存包含Hibernate對象的舊歷史記錄,就像PersistSet一樣,它不會被存儲在數據庫中... Stranggeee ....這是預期的行爲嗎?...我更喜歡臭蟲的味道,或者我在這裏錯過了一些東西。 ..

如果我調試Hibernate代碼,收集條目從未被標記爲更新/重建的方法Collections.prepareCollectionForUpdate(),因爲loadedPersister和currentPersister是出於某種原因相同......

有誰知道?

回答

2

我相信在測試的最後statment應斷言空:assertNotNull(dec.getStatusHistory()); // ERROR, is empty like before總之:

您應該使用clear方法,而不是刪除一組。

因此,使用:的

dec.getStatisHistory().clear(); 
... 
assertTrue(dec.getStatusHistoryHistory.isEmpty()); 

代替:

dec.setStatusHistory(null); 
... 
assertNull(dec.getStatusHistory()); 

在Hibernate是永諾一個壞主意,除去休眠mannaged集合。

在我看來

BTW,甚至更簡潔的方法有一個空集,而不是空

新增

你可以試試如果你真的需要刪除收集在添加之前將其內容複製到新集合中。

dec.setStatusHistory(new HashSet(history)); 
+0

是的,它必須是assetNotTrue,謝謝....你的聲明是不正確的,嘗試它。父母之間的關係當然也需要明確,孩子也是一個實體,但是當孩子也是一個實體的時候,就像他的父母一樣。在這種情況下,Hibernate具有完全控制權並能夠發出變化信號。自己測試一下,你會看到它。謝謝 – edbras 2011-01-30 11:35:51