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.setId(10); changedEmp.setName("New Name"); //session.update(changedEmp); // Throws NonUniqueObjectException session.merge(changedEmp); 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.