Hibernate: Understanding Cascade Types

We want to understand what happens when we have CascadeType.REMOVE in a @ManyToOnerelationship.

From the Hibernate Community Documentation

11.11. Transitive persistence

It is quite cumbersome to save, delete, or reattach individual objects, especially if you deal with a graph of associated objects. A common case is a parent/child relationship. Consider the following example:

If the children in a parent/child relationship would be value typed (e.g. a collection of addresses or strings), their life cycle would depend on the parent and no further action would be required for convenient “cascading” of state changes. When the parent is saved, the value-typed child objects are saved and when the parent is deleted, the children will be deleted, etc. This works for operations such as the removal of a child from the collection. Since value-typed objects cannot have shared references, Hibernate will detect this and delete the child from the database.

Now consider the same scenario with parent and child objects being entities, not value-types (e.g. categories and items, or parent and child cats). Entities have their own life cycle and support shared references.

Removing an entity from the collection does not mean it can be deleted, and there is by default no cascading of state from one entity to any other associated entities. Hibernate does not implement persistence by reachability by default.

And moreover

In case you are using annotations you probably have noticed the cascade attribute taking an array of CascadeType as a value. The cascade concept in JPA is very is similar to the transitive persistence and cascading of operations as described above, but with slightly different semantics and cascading types:

  • CascadeType.PERSIST: cascades the persist (create) operation to associated entities if persist() is called or if the entity is managed
  • CascadeType.MERGE: cascades the merge operation to associated entities ifmerge() is called or if the entity is managed
  • CascadeType.REMOVE: cascades the remove operation to associated entities ifdelete() is called
  • CascadeType.REFRESH: cascades the refresh operation to associated entities ifrefresh() is called
  • CascadeType.DETACH: cascades the detach operation to associated entities ifdetach() is called
  • CascadeType.ALL: all of the above




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s