Tom
Tom

Reputation: 3176

Will Hibernate saveOrUpdate method delete children?

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?

Upvotes: 7

Views: 4805

Answers (2)

skaffman
skaffman

Reputation: 403581

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.

Upvotes: 5

Rafael
Rafael

Reputation: 2443

By default, it will not. You could use @Cascade(CascadeType.DELETE_ORPHANS) to achieve that.

Upvotes: 0

Related Questions