What is the difference between cascade & inverse in hibernate, what are they used for?

Viewed 58860

How to use cascade and inverse in hibernate? What is the procedure/tag to define them? Are they related to each other and how are they useful?

3 Answers

These are orthogonal concepts.

In associations, one of the side must be marked as inverse by using inverse attribute or mappedBy attribute (many side in one-to-many/ many-to-one association and either side in many-to-many association). This information is needed for Hibernate to correctly determine, how Java classes (object-oriented association) will be mapped to the database tables(relational association).

What about cascading - you can explicitly specify for Hibernate to perform operations on associated entities:

  • CascadeType.PERSIST - When the save() or persist() method is called for the owner, all the associated entities are also saved;
  • CascadeType.REMOVE - When the delete() method is called for the owner, all the associated entities are also deleted;
  • CascadeType.MERGE - When the merge() method is called for the owner, all the associated entities are also merged to managed/ persisted state;
  • CascadeType.REFRESH - When the refresh() method is called for the owner, all the associated entities are also refreshing from their database representation;
  • CascadeType.DETACH - When the session with which this entity was associated is closed, all the related entities would in the detached state;
  • CascadeType.ALL - Includes all the cascade operations;
  • "orphan removal" - removes associated entity from the database, when this entity removed from the relationship.
Related