Make delicious recipes!


Persist vs Merge

JPA's EntityManager provides several methods to manage the persistence of an entity.
Two such methods are:
void persist(Object entity) 
//Makes an instance managed and persistent.


<T> T merge(T entity) 
//Merges the state of the given entity into the current persistence context and
//returns the managed instance that the state was merged to.
Both these methods save the given entity into the database but there is a subtle difference in their working.

Persist makes the given instance a managed instance.
So future updates to the entity are tracked until the current transaction is active.

Merge creates a clone from the supplied entity, and makes that clone a managed instance.
The instance passed to merge() does not become managed.
So any changes made to that instance are not committed in the currently active transaction - unless merge is called again.

Example:

Case 1: Name will be persisted since "p" becomes a managed instance
Person p = new Person();
tx.begin();
em.persist(p); 
p.setName("Harry"); 
tx.commit();


Case 2: Name will NOT be persisted because "p" remains unmanaged
Person p = new Person();
tx.begin();
em.merge(p);
p.setName("Harry");
tx.commit();


Case 3: Name will be persisted since changes are made to managed instance "p2"
Person p = new Person();
tx.begin();
Person p2 = em.merge(p);
p2.setName("Harry"); 
tx.commit();






Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal