Monday, December 7, 2015

JPA EntityManager Merge vs Persist

Here's a quick short post. Putting it here, since it has been tremendously useful for me. I hope this will help others as well.

There have been several questions on SO about merge() and persist() operations. But I find that it is not just about one resulting to an UPDATE SQL command, and the other resulting to an INSERT SQL command.

Results of merge() and persist()

Instead of pasting relevant sections from the JPA 2.1 specification in this post, I've created a summary table of the results of the said operations. This is based on sections 3.2.2 (Persisting an Entity Instance) and 3.2.7.1 (Merging Detached Entity State) of the JPA 2.1 specification.

Operation State Result
persist new becomes managed
persist managed ignored (but cascaded)
persist removed becomes managed
persist detached throws exception or commit fails
Operation State Result
merge new becomes managed
merge managed ignored (but cascaded)
merge removed throws exception or commit fails
merge detached becomes managed

As you can see, both merge() and persist() operations treat new and managed entities the same way. But they only differ in the way they treat removed and detached entities.

Closing Thoughts

So, the next time you think that persist() results to an INSERT, and merge() results to an UPDATE, think again!

Here's my take. I personally prefer to use merge() operation to handle new, managed, and detached entities.

But for removed entities (which can only happen when you programmatically remove it), I use persist(). But then again, it's rare (in my experience) to remove an entity, and then reverse its removal in the same persistence context.

No comments:

Post a Comment