This post is going to explain when to use persist and when to use merge. Persist The persist operation must be used only for new entities.
From JPA perspective, an entity is new when it has never been associated with a database row, meaning that there is no table record in the database to match the entity in question.
For instance, when executing the following test case: The Map key is formed of the entity type its class and the entity identifier. The TABLE strategy behaves like SEQUENCE, but you should avoid it at any cost because it uses a separate transaction to generate the entity identifier, therefore putting pressure on the underlying connection pool and the database transaction log. Merge Merging is required only for detached entities.
Assuming we have the following entity: The detached entity can be modified, and, to propagate these changes, the entity needs to be reattached to a new Persistence Context: This way, the dirty checking mechanism can detect any state change and propagate it to the database.
Considering that the Post entity requires that identifiers are manually assigned: Id private Long id; When using merge instead of persist: Long for which Hibernate can check for nullability, instead of a primitive e. The reason why I wanted to show you this example is that you might happen to use a save method like this one offered by Spring Data SimpleJpaRepository: If you ever use an assigned identifier generator, you have to remember to add a Java Wrapper Version property, otherwise, a redundant SELECT statement is going to be generated.
However, while reviewing lots of projects, I came to realize that the following anti-pattern is rather widespread: Even if we remove it, Hibernate will still issue the UPDATE statement since the entity is managed and any state change is propagated as long as the currently running EntityManager is open. This is an anti-pattern because the save call fires a MergeEvent which is handled by the DefaultMergeEventListener which does the following operations: If the entity has child associations and the merge operation is also cascaded from parent to child entities , the overhead is even greater because each child entity will propagate a MergeEvent and the cycle continues.
If you enjoyed this article, I bet you are going to love my Book and Video Courses as well. Conclusion While a save method might be convenient in some situations, in practice, you should never call merge for entities that are either new or already managed.
For new entities, you should always use persist, while for detached entities you need to call merge. Subscribe to our Newsletter.