Video in progress
What's the difference between persist() and merge()?
persist() makes the new (transient) object itself managed and returns nothing. merge() copies the state of a detached or new object onto a managed copy and returns that copy. The object you passed in does not become managed.
📖 Answer
The most common mistake is throwing away the result of merge:
User detached = loadFromSomewhere(); // detached
em.merge(detached);
detached.setEmail("x@y.uz"); // this change is NOT saved
User managed = em.merge(detached);
managed.setEmail("x@y.uz"); // this one is saved
What happens inside merge: Hibernate finds the entity by id, in the context or in the database (with a SELECT), copies the fields of the passed object onto it, and returns the managed copy.
If you pass a detached object (one that has an id) to persist, you get EntityExistsException or a "detached entity passed to persist" error.
save() in Spring Data picks between the two: if the entity is new (id == null or a null @Version) it calls persist, otherwise merge. That's why for entities where you assign the id yourself, save() sends a SELECT first every time. People are often surprised when they see this in the logs.
Sign up to mark studied questions and save your progress.