Easy learning with example program codes

What is the difference between session.merge vs session.update in hibernate?

Update and Merge both work on detached instances, ie instances which have a corresponding entry in the database but which are currently not attached to a Session. Both methods are used to convert these object into persistence state from detached state.
The update tries to reattach the instance, that means that there may be no other instance of the persistent entity attached to the Session right now otherwise an exception is thrown. i.e. update method cannot be used when the same object exists in the session.

The merge copies all values to a persistent instance in the session. The input object is not changed. So merge is more general than update, but may use more resources. i.e. The merge method will work fine when the same object exists in the session.


Employee currentEmp = (Employee)session.get(Employee.class, 10);
   System.out.println("Before merge: " + currentEmp.getName());
Employee changedEmp = new Employee();
changedEmp.setName("New Name");
//session.update(changedEmp); // Throws NonUniqueObjectException
System.out.println("After merge: " + current.getName());


In the above example we have loaded an Employee object of id ‘10’. After that we have created a new Employee object ‘changedEmp’ with same ID ‘10’. Now if we try to call update method on this ‘changedEmp’ object, then Hibernate will through a NonUniqueObjectException, because the same object (Employee) with Id ‘10’ already exists in session.

But merge() method will work fine and the name will get changed and saved into the database. After this on printing the current object, it will print the latest changed value, since when the merge occurs the value loaded in session gets changed.

Sign Up/ Sign In
Ask a Question

Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at


We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on

Copyright © 2018 CodesJava Protection Status SiteMap Reference: Java Wiki