EntityManager.merge()
can insert new objects and update existing ones.
Why would one want to use persist()
(which can only create new objects)?
EntityManager.merge()
can insert new objects and update existing ones.
Why would one want to use persist()
(which can only create new objects)?
There are some more differences between
merge
andpersist
(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: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 anIllegalArgumentException
.D3. If you decided to take care manually of your IDs (e.g by using UUIDs), then a
merge
operation will trigger subsequentSELECT
queries in order to look for existent entities with that ID, whilepersist
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
.Scenario X:
Table:Spitter (One) ,Table: Spittles (Many) (Spittles is Owner of the relationship with a FK:spitter_id)
This scenario results in saving : The Spitter and both Spittles as if owned by Same Spitter.
Scenario Y:
This will save the Spitter, will save the 2 Spittles But they will not reference the same Spitter!
I noticed that when I used
em.merge
, I got aSELECT
statement for everyINSERT
, even when there was no field that JPA was generating for me--the primary key field was a UUID that I set myself. I switched toem.persist(myEntityObject)
and got justINSERT
statements then.