JPA merge and persist: What’s Difference?

In JPA, use merge when dealing with detached entities; and use persist to explicitly add a new entity to the database without checking if it already exists.

jpa 2

JPA’s EntityManager class provides persist() and merge() methods to save the state of an entity in the database. Though both methods look the same, they have subtle differences which we must know to effectively use in the application program.

1. Difference between Merge and Persist

Let’s start with a quick summary before diving deep into the methods.

FeatureMergePersist
BehaviorAdds or updates an entity to the persistence context, merging its state if entity already existsAdds a new entity to the persistence context
When to UseWhen dealing with detached entities that need to be synchronized with the databaseWhen adding a new entity to the database
Managed vs. Detached EntitiesWorks with both managed and detached entitiesSpecifically for new entities not managed by the persistence context
Exception HandlingThrows EntityExistsException if the entity already exists in the persistence context or databaseThrows EntityExistsException if the entity already exists in the persistence context or database
Return ValueReturns the managed entity instanceN/A (Void method)
Cascade BehaviorCascades to related entities if specified in mappingsCascades to related entities if specified in mappings
Performance ImpactCan potentially result in additional database calls and performance overhead due to state synchronizationGenerally performs better as it only inserts entities

2. EntityManager.persist() Method

In JPA, the persist() method adds a new entity to the persistence context. The entity is saved into the database when the transaction is committed. Note that the persist() throws an EntityExistsException if the entity already exists in the persistence context or if an entity with the same identifier already exists in the database.

The persist() method is used to when we want to add a new record to the database.

@Transactional
public void addPerson(Person newPerson) {
    entityManager.persist(newPerson);
}

3. EntityManager.merge() Method

The merge() method can be used for adding new entities as well as updating existing entities, also. More specifically, the merge() method adds entities to the persistence context or updates detached entities.

The main difference between merge() and persist() is seen in the update operation. add entities to the persistence context or update detached entities. In merge() operation, if an entity with the same identifier already exists in the persistence context, its state will be copied over to the managed entity instance. If no such entity exists, a new one will be created.

After the merge operation is finished, it returns the managed entity instance.

@Transactional
public Person updatePerson(Person updatedPerson) {
    return entityManager.merge(updatedPerson);
}

4. Summary

As discussed in this short JPA tutorial, we should use merge when dealing with detached entities; and use persist to explicitly add a new entity to the database without checking if it already exists.

Both methods show different behavior when an entity with the same identifier already exists, so we should use the appropriate method based on the requirements.

Happy Learning!!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.