我继承了一个 hibernate 映射,但无法将子节点从一个父节点移动到另一个父节点。要么我得到重复的引用,要么我得到一个错误。
我在树上有位置。我想将一个叶节点移动到另一个叶位置。在代码中我试图这样做:
GeographicLocation oldParent = location.getParent();
location.setParent(newParent);
newParent.getChildren().add(location);
oldParent.getChildren().remove(location);
原因:
org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): [com.test.GeographicLocation#11]
如果我删除 oldParent.getChildren().remove(location)
行,newParent
节点正确指向 child ,但 oldParent
仍然有对 child 的引用(!)。
来自 hibernate 配置文件的片段:
<class name="GeographicLocation" table="GeographicLocation">
<id column="GeographicLocationId" name="geographicLocationId" type="java.lang.Long">
<generator class="native">
<param name="sequence">GeographicLocationId</param>
</generator>
</id>
<many-to-one class="com.test.GeographicLocation"
foreign-key="ParentFK" name="parent">
<column name="parent"/>
</many-to-one>
<bag cascade="all,delete-orphan" inverse="true" lazy="false" name="children">
<key column="parent" not-null="true"/>
<one-to-many class="com.test.GeographicLocation"/>
</bag>
我使用 Hibernate 的时间并不长。我的理解是 location
节点是一个托管对象,在修改时会自行保存。由于 hibernate 配置文件指定 cascade=all
对集合的更改也将保存对子项的更改。但是,我似乎找不到删除旧引用的合法方法。有帮助吗?
最佳答案
我将从映射中删除 delete-orphan
,因为它表示一旦您从集合中删除一个元素,它就应该被删除(这显然不是您想要的)。
关于java - Hibernate 集合未在子移动时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12807511/