HibernateException - A collection with cascade="all-delete-orphan" was no longer referenced by the o

本文参考自:http://cristian.sulea.net/blog.php?p=2014-06-28-hibernate-exception-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-owning-entity-instance

异常:

org.hibernate.HibernateException:
A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: entities.Parent.childs
    at org.hibernate.engine.internal.Collections.processDereferencedCollection(Collections.java:116)
    at org.hibernate.engine.internal.Collections.processUnreachableCollection(Collections.java:67)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushCollections(AbstractFlushingEventListener.java:245)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:100)
    at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:55)
    at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1099)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1528)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
    at org.hibernate.internal.CriteriaImpl.uniqueResult(CriteriaImpl.java:396)
    ...

解决办法:

当在集合中需要新增或者删出元素的时候,我们需要修改这个集合而不是重新指定一个新的集合到parent类中:

parent.getChildren().clear();
parent.getChildren().addAll(someNewSetOfChildren);
或者在parent的entity类中:
public void setChildren(Set someNewSetOfChildren) {
 
    //
    // This will override the set that Hibernate is tracking.
    // this.children = someNewSetOfChildren;
 
    this.children.clear();
    this.children.addAll(someNewSetOfChildren);
}



你可能感兴趣的:(HibernateException - A collection with cascade="all-delete-orphan" was no longer referenced by the o)