88

What does the CascadeType.REFRESH actually do?

The definition for it is

When we refresh an entity all the entities held in this field refresh too

but what does this mean in practice? Could someone please give me a simple example?

2 Answers 2

130

The individual CascadeType descriptions can be a bit confusing, but there's an easy way to figure it out from the general case.

For any of the CascadeType values, it means that if operation X is called on an instance using the EntityManager interface, and that instance has references to other entity instances, and that association has CascadeType.X defined, then the EntityManager operation will also be applied to that associated entity.

So EntityManager.refresh() is defined as :

Refresh the state of the instance from the database, overwriting changes made to the entity, if any.

So if entity A has a reference to entity B, and that reference is annotated with @CascadeType.REFRESH, and EntityManager.refresh(A) is called, then EntityManager.refresh(B) is implicitly called also.

3
  • I know this is an old post, but using your example of A and B above, if the instance of B is currently detached, would a CascadeType.PERSIST cause B to become persistent? I'm using Hibernate's JPA implementation.
    – Andy
    Oct 8, 2012 at 14:08
  • 5
    Answered my own question. Answer is no. You must call save on the object for it to become persistent.
    – Andy
    Oct 8, 2012 at 14:25
  • What will happen if I merge an object which is in the persistent state? Nov 4, 2019 at 13:33
10

Retrieval by Refresh: Managed objects can be reloaded from the database by using the refresh method:

The content of the managed object in memory is discarded (including changes, if any) and replaced by data that is retrieved from the database. This might be useful to ensure that the application deals with the most up to date version of an entity object, just in case it might have been changed by another EntityManager since it was retrieved.

Source: http://www.objectdb.com/java/jpa/persistence/retrieve

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.