Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA merge vs. persist [duplicate]

So far, my preference has been to always use EntityManager's merge() take care of both insert and update. But I have also noticed that merge performs an additional select queries before update/insert to ensure record does not already exists in the database.

Now that I am working on a project requiring extensive (bulk) inserts to the database. From a performance point of view does it make sense to use persist instead of merge in a scenario where I absolutely know that I am always creating a new instance of objects to be persisted?

like image 869
phewataal Avatar asked Dec 12 '11 04:12

phewataal


People also ask

What is the difference between persist and merge in JPA?

Persist should be called only on new entities, while merge is meant to reattach detached entities. If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.

When to Use merge and persist?

Persist takes an entity instance, adds it to the context and makes that instance managed (i.e. future updates to the entity will be tracked). Merge returns the managed instance that the state was merged with. It does return something that exists in PersistenceContext or creates a new instance of your entity.

What is JPA merge?

JPA's merge method copies the state of a detached entity to a managed instance of the same entity. Hibernate, therefore, executes an SQL SELECT statement to retrieve a managed entity from the database.


2 Answers

It's not a good idea using merge when a persist suffices - merge does quite a lot more of work. The topic has been discussed on StackOverflow before, and this article explains in detail the differences, with some nice flow diagrams to make things clear.

like image 144
Óscar López Avatar answered Sep 23 '22 19:09

Óscar López


I would definitely go with persist persist() if, as you said:

(...) I absolutely know that I am always creating a new instance of objects to be persisted (...)

That's what this method is all about - it will protect you in cases where the Entity already exists (and will rollback your transaction).

like image 24
Piotr Nowicki Avatar answered Sep 25 '22 19:09

Piotr Nowicki