Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active April 30, 2020 07:18
Show Gist options
  • Save rponte/1690560 to your computer and use it in GitHub Desktop.
Save rponte/1690560 to your computer and use it in GitHub Desktop.
difference between entityManager.persist() and entityManager.merge()

QUESTION:

EntityManager.merge() can insert new objects and update existing ones.

Why would one want to use persist() (which can only create new objects)?

ANSWER:

Either way will add an entity to a PersistenceContext, the difference is in what you do with the entity afterwards.

Persist takes an entity instance, adds it to the context and makes that instance managed (ie future updates to the entity will be tracked)

Merge creates a new instance of your entity, copies the state from the supplied entity, and makes the new copy managed. The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again).

@wbotelhos
Copy link

The problem is that everyone, including me, uses the return of the merge that is after all, managed. :P

Good explanation!

@rponte
Copy link
Author

rponte commented Jan 28, 2012

When I found that post I was looking for the difference between session.saveOrUpdate() e entityManager.merge(), anyways, I learned something interesting in the end.

@wladekAiro
Copy link

Ok.. Thanks for the xplanation.... But how does someone make use of the merge. I am new to spring jpa and hibernate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment