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

如果我创建一个包含一些条目的新 Set 并存储它,一切正常,但是当我存储包含 Hibernate 对象的旧历史记录(如 PersistSet)时,它不会存储在数据库中...... Stranggeee...... . 这是预期的行为吗?...我闻起来更像是虫子,或者我在这里遗漏了一些东西...

如果我调试 Hibernate 代码,则集合条目永远不会在 Collections.prepareCollectionForUpdate() 方法中标记为已更新/重新创建,因为由于某种原因,loadedPersister 和 currentPersister 是相同的......

有人知道吗?

4

1 回答 1

2

我相信你的测试中的最后一条语句应该是 assert NOT Null:assertNotNull(dec.getStatusHistory()); // ERROR, is empty like before不管怎样:

您应该使用该clear方法而不是删除该集合。

所以使用:

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

代替:

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

在休眠中,删除休眠托管集合总是一个坏主意。

顺便说一句,在我看来,使用空集而不是 null 是一种更简洁的方法

添加

如果您确实需要删除集合,您可以尝试在添加之前将其内容复制到新集合中。

dec.setStatusHistory(new HashSet(history));
于 2011-01-28T13:40:00.863 回答