Hibernate merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state.

session.merge()

The merge() method is used when we want to change a detached entity into the persistent state again, and it will automatically update the database. The main aim of the merge() method is to update the changes in the database made by the persistent object. The merge() method is provided by the Session interface and is available in org.hibernate.session package.

There are two merge() methods available in the Session interface with different parameters:

  • merge(Object object)
  • merge(String entityName, Object object)

Both of the above methods perform the same functions.

How to use session.merge()

Employee employee = session.merge(emp);       

session.update()

The update() method is used to save the object in the database. We can use the update() method when the Session does not contain any persistent object with the same primary key. If the Session has a persistent object with the same primary key, it will throw an exception.

This method adds an entity object to the persistent state, and more changes are tracked and saved when the transaction is committed. The update() method does not return anything. The update() method is provided by the Session interface and is available in org.hibernate.session package.

There are two update() methods available in the Session interface with different parameters:

  • update(Object object)
  • update(String entityName, Object object)

Both of the above methods perform the same functions.

How to use session.update()

Employee employee = session.update(emp);

Difference between merge() and update

               Parameter                   merge()                update()
Usage A merge() method is used to update the database. It will also update the database if the object already exists. An update() method only saves the data in the database. If the object already exists, no update is performed.
Exception It will update the object in the database without any exception. When creating a detached object into persistent state, it will throw an exception only when the Session contains a persistent object with the same primary key.