What are the cascade types in JPA?

4

I'm looking for information on the cascade types that exist and how they work in relational modeling with JPA. The types I found explanations were:

  • NONE = Do not do anything with the object (default)

  • MERGE = Update children when updating parent only if already persistent

  • PERSIST = Save child when saving parent

  • REFRESH = Saves parent and keeps child unchanged
  • REMOVE = Removes child when removing parent and vice versa

  • ALL = Performs all cascade operations

I have the following doubts:

  • Is the working explanation of these types of cascade correct?

  • Mapping with mappedBy should put cascade on parent object only?

  • asked by anonymous 28.03.2017 / 22:35

    1 answer

    3

    There are six cascade types (CascadeType) in the JPA specification. They are:

    • ALL = Performs all cascading operations
    • DETACH = Performs cascading detach operation
    • MERGE = Performs cascade merge operation
    • PERSIST = Performs the cascade persist operation
    • REFRESH = Perform cascade refresh operation
    • REMOVE = Performs cascade remove operation
    Performing cascade operations only makes sense in Parent-Child relationships (the state transition of the Parent entity being cascaded into the Child entity). Although it is possible to map the cascade in the opposite direction (Son - Father) is not very useful and can not be considered a good practice.

      
  • Is the explanation of these cascade types correct?
  •   
    • When MERGE is run, it also persists the children if they have not yet been persisted.
    • REFRESH does not save, but updates the entity with the bank information.
      
  • Mapping with mappedBy should cascade be placed only on the parent object?
  •   
    • It is a good practice for cascading operations to be done from parent to child, rather than the reverse, even though it is valid.
      
  • I found cascade references DETACH and LOCK, how do they work?
  •   
    • Cascade DETACH causes the detach operation, when executed on the parent, to also run on the child. We say that an entity is detached when it is not being managed by the EntityManager. This happens when we execute the EntityManager detach method, when the transaction is rolled over or rollback.
    • Cascade LOCK is not part of JPA but Hibernate. Basically when you acquire a lock on the parent entity, this operation will also be performed on the children.
    23.04.2017 / 04:41