EntityManager.merge()
can insert new objects and update existing ones.
Why would one want to use persist()
(which can only create new objec
There are some more differences between merge
and persist
(I will enumerate again those already posted here):
D1. merge
does not make the passed entity managed, but rather returns another instance that is managed. persist
on the other side will make the passed entity managed:
//MERGE: passedEntity remains unmanaged, but newEntity will be managed
Entity newEntity = em.merge(passedEntity);
//PERSIST: passedEntity will be managed after this
em.persist(passedEntity);
D2. If you remove an entity and then decide to persist the entity back, you may do that only with persist(), because merge
will throw an IllegalArgumentException
.
D3. If you decided to take care manually of your IDs (e.g by using UUIDs), then a merge
operation will trigger subsequent SELECT
queries in order to look for existent entities with that ID, while persist
may not need those queries.
D4. There are cases when you simply do not trust the code that calls your code, and in order to make sure that no data is updated, but rather is inserted, you must use persist
.