Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is merging in JPA ever necessary for attached entities?

Tags:

java

jpa

Is it correct that I never need to use EntityManager#merge(), as long as I only deal with attached managed entities? In other words, calling merge() on an attached managed entity has no effect?

Or are there circumstances where merging would serve a purpose? I find the name suggests that I could use it to deal with an OptimisticLockException... :)

Edit: In very simple terms, my understanding of a managed Entity is that modifications of its properties/fields get persisted to the DB at the end of the transaction.

like image 896
Hank Avatar asked Sep 12 '11 12:09

Hank


People also ask

When to Use merge and persist?

Persist takes an entity instance, adds it to the context and makes that instance managed (i.e. future updates to the entity will be tracked). Merge returns the managed instance that the state was merged with. It does return something that exists in PersistenceContext or creates a new instance of your entity.

How does JPA merge work?

JPA's merge method copies the state of a detached entity to a managed instance of the same entity. Hibernate, therefore, executes an SQL SELECT statement to retrieve a managed entity from the database.

What is the difference between Merge and persist in hibernate?

persist(Object entity): Make an instance managed and persistent. merge(T entity): Merge the state of the given entity into the current persistence context.

How do you persist detached entity in JPA?

update, attach the passed entity to the persistence context while EntityManager. merge method copies the state of the passed object to the persistent entity with the same identifier and then return a reference to that persistent entity. The object passed is not attached to the persistence context.


1 Answers

The specification states that:

If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

like image 100
DataNucleus Avatar answered Oct 04 '22 17:10

DataNucleus