Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does CascadeType.REFRESH actually do?

Tags:

java

jpa

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?

like image 471
Kim L Avatar asked Sep 10 '09 06:09

Kim L


People also ask

What is CascadeType refresh?

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.

What does CascadeType all do?

CascadeType. ALL specifies that when a Customer is created, if there is any Address association, then that Address will be created as well(CascadeType. PERSIST). If the Customer is deleted from persistence storage, the Address table will be deleted(CascadeType.

What does CascadeType remove do?

As stated earlier, marking a reference field with CascadeType. REMOVE is a way to delete a child entity or entities whenever the deletion of its parent happens. In our case, an OrderRequest has a ShipmentInfo, which has a CascadeType. REMOVE.

What does CascadeType merge do?

CascadeType. MERGE : cascade type merge means that related entities are merged when the owning entity is merged.


2 Answers

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.

like image 144
skaffman Avatar answered Sep 19 '22 00:09

skaffman


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

like image 30
Ethos Avatar answered Sep 19 '22 00:09

Ethos