Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Hibernate saveOrUpdate method delete children?

Tags:

java

hibernate

I have an application that loads objects via hibernate and then passes those objects to another tier as detached objects. Any changes to those objects are sent back down to the hibernate tier where I call saveOrUpdate() on those objects.

Will hibernate delete one-to-many relationship child objects contained in a collection in the objects that are passed into saveOrUpdate() if I simply remove the child object from the collection before calling saveOrUpdate()?

If not, then how would this typically be accomplished in a hibernate application that uses detached objects?

like image 975
Tom Avatar asked May 08 '12 20:05

Tom


1 Answers

Will hibernate delete one-to-many relationship child objects contained in a collection in the objects that are passed into saveOrUpdate() if I simply remove the child object from the collection before calling saveOrUpdate()?

No, not by default. Such child objects are known as "orphans" in this context, assuming that some other entity doesn't also have a reference to them.

This is discussed in the docs, 11.11. Transitive persistence:

A special cascade style, delete-orphan, applies only to one-to-many associations, and indicates that the delete() operation should be applied to any child object that is removed from the association. Using annotations there is no CascadeType.DELETE-ORPHAN equivalent. Instead you can use the attribute orphanRemoval as seen in Example 11.4, “@OneToMany with orphanRemoval”. If an entity is removed from a @OneToMany collection or an associated entity is dereferenced from a @OneToOne association, this associated entity can be marked for deletion if orphanRemoval is set to true.

like image 193
skaffman Avatar answered Sep 25 '22 17:09

skaffman