java - 不要更改对具有级联 ="all-delete-orphan"的集合的引用

标签 java hibernate hibernate-onetomany

我收到一个错误:

Don't change the reference to a collection with cascade="all-delete-orphan"

尝试以下操作时:

beginTx();
Parent parent = new Parent();
Child child = new Child();
parent.addChild(child);
getSession().save(parent);
commitTx();
closeSession();

beginTx();
//id is the primary key
child.setID(null);
getSession().update(child);
commitTx();
closeSession();

父子关系是一对多,cascade = 'all-delete-orphan'。

class Parent {
Set child;
}


<set name="child" table="Child" cascade="all-delete-orphan" inverse="true">
    <key column="FK"></key>
    <one-to-many class="Child"/>
</set>

知道为什么会抛出这个异常吗? 为什么在主键上设置 null 会导致此异常,即使实体处于分离状态?

最佳答案

如果您使用 cascade=all-delete-orphan 加载具有集合的实体,然后删除对该集合的引用,则通常会发生此异常。

不要替换这个集合。始终使用 collection.clear() 删除所有关联的子条目,以便孤立删除算法可以检测到更改。如果你想删除任何特定的 child ,你只需要从集合中删除它。一旦从集合中移除,它将被视为孤儿并被删除。

关于java - 不要更改对具有级联 ="all-delete-orphan"的集合的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18910641/

相关文章:

java - 使用 Android Intent 共享文件 : File extension is removed

java - 无法从 Java 项目访问终端中的 .png 文件

JavaFX 8 : Stage insets (window decoration thickness)?

hibernate - 如何在 Hibernate 中连接到多个数据库

json - Hibernate @OneToMany 关系导致 JSON 结果中出现无限循环或空条目

java - .NET - .NET 的安全框架

xml - 错误 : No persistence units parsed from {classpath*:META-INF/persistence. xml}

java - Spring事务性注解应该放在哪里,在哪一层?

java - Hibernate:与多键表的键之一连接

java - 一对多关系中的 CascadeType 问题