1.

What is the difference between update and merge method?

Answer»

Both these methods are used when the object has to be converted from detached to PERSISTENT state.The differences between update() and merge() methods are as below.

No.The update() methodmerge() method
1.Update method is called when an object needs to be edited. The method is called if the session doesn’t contain an already persistent state with the same id.Merge method is called when a persistent entity instance has to be updated with the new values from a detached entity instance

 Let's try to understand the difference by the EXAMPLE given below: 

...    SessionFactory sf = obj.buildSessionFactory();    Session S1 = sf.openSession();    Employee e1 = (Employee) s1.get(Employee.class, Integer.valueOf(101));//passing id of employee  s1.saveOrUpdate(e1);  s1.close();  e1.setSalary(70000);    Session S2 = sf.openSession();    Employee e2 = (Employee) s2.get(Employee.class, Integer.valueOf(101));//passing same id  Transaction tx=s2.beginTransaction();    s2.update(e1); //throws exception  s2.merge(e1);    tx.commit();    s2.close();  

In a single session, only one persistent object can be maintained with a specific primary KEY. In the above example, the Employee object e1 is stored in the session cache. When the session is closed, e1 will be converted to detached state. If we have to update the Employee object e1 with the new values, we need another session. In the second session, if we try to update e1, an exception is thrown. Now we will call merge in session2 and changes of e1 will be merged in e2 as e2 has the same id as e1. 



Discussion

No Comment Found