java - Hibernate 集合未在子移动时更新

标签 java hibernate

我继承了一个 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/

相关文章:

java - 为什么SparkSession一个action执行两次?

java - 在预期之前执行的代码块,代替 boolean 值

spring - 如何使用 Spring Data JPA 和 Spring Security 实现 AuditorAware?

java - 如何测试Hibernate Session是否打开?

java - 在 JAVA 的企业应用程序中使用静态方法

java - H2:在所有其他计算机上均出现错误

java - 如何测试仅调用存储库(dao)层的CRUD服务?

java - 如何使用 CriteriaQuery 查询 OneToOne 实体的特定值

java - 应用程序被强制关闭

java - 多个数据库的事务管理器