Tuesday, September 18, 2012

HibernateException – A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance


I believe most of us have encountered this error while working with NHibernate. This error comes due to the way NHibernate works and the way we developers habitual of coding :) Doing retrieval and updation of a parent object in the same transaction confuses NHibernate about what to do with the 2 child collections available in the session for the updated parent object and thus this error is thrown. To explain further, let us take an example:

There is an object DOCUMENT with cascade="all-delete-orphan" settings with child collection of PARAGRAPH with one-to-many relationship between them.

If the parent is detached and is then updated then the following lines of code will work:
public void setParagraph(Set dSet)
{    
    this.paragraphs = dSet;

In case DOCUMENT is not fetched and updated in the same transaction then below code lines works:

public void setParagraph(Set<Paragraph> dSet)
{    
    // this.paragraphs = dSet; //This will override the set that Hibernate is tracking.
    this.paragraphs.Clear();
    this.paragraphs.Add(dSet);

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.