The differences between update() and merge() methods are given below.
No. The update() method merge() method
1) Update means to edit something. Merge means to combine something.
2) update() should be used if the session doesn't contain an already persistent state with the same id. It means an update should be used inside the session only. After closing the session, it will throw the error. merge() should be used if you don't know the state of the session, means you want to make the modification at any time.
Let's try to understand the difference by the example given below:
...
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing id of employee
session1.close();
e1.setSalary(70000);
Session session2 = factory.openSession();
Employee e2 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing same id
Transaction tx=session2.beginTransaction();
session2.merge(e1);
tx.commit();
session2.close();
After closing session1, e1 is in detached state. It will not be in the session1 cache. So if you call update() method, it will throw an error.
Then, we opened another session and loaded the same Employee instance. If we call merge in session2, changes of e1 will be merged in e2.