Merge the state of the given entity into the current persistence context. The merge method’s major task is to transfer the state from an unmanaged entity (detached entity) to its managed counterpart within the persistence context. In other words merge will reattach the detached entity to the persistence context.

How merge works?

When you call merge method,

  • if the given entity is already in the persistence context (session), no action is taken, except for cascades
  • if the given  entity is detached, a copy (object’) is returned, which is attached (managed). But an object with the same identifier exist in the current entity manager, then the state of the detached object is copied into the current persistent entity, and it (the current) is returned
  • if the given entity is transient (new instance), it is saved and a persistent (and managed) copy is returned.

For better understanding see JPA entity lifecycle.

Code Example :

Student Table


Testing Merge operation :

Console Output :

Download Application – (10 KB)