Be Careful When Using Parent-Child Associations in Hibernate

Parent-child relationships are a special case of more general 1:M associations. They are simply part-whole relationships and for Hibernate it is not meaningful that parts (childs) should exist without belonging a whole (parent).

Parent-child association is specified with orphanRemoval attribute of @OneToMany annotation. Hibernate achieves this by employing a special persistent collection implementation.

First thing you should be aware of that when a child entity is just removed from its containing collection (eg, childs.remove(child)) Hibernate issues an SQL DELETE statement at flush time for that child entity without expecting an explicit session.delete(child) call. Remove operations are tracked by that persistent collection and removal of a child means that it becomes orphan, and orphan children should be immediately deleted.

Another important point is that when you want to get rid of all of the children in a collection, just call childs.clear(). If you try to set parent’s collection property value to NULL (for example, parent.setChilds(null)) you will get an HibernateException with the following message; “A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance” This message tells us that collection instance which is used to manage parent-child relationship is de-referenced by its parent. In order words, connection between two is just lost. However this exception only arises when you perform NULL set operation to attached parent entity. If parent is detached. You can safely set its childs property to NULL and then reattach it to the session. Reattachment will cause all of its childs to be deleted as well.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.