What is the difference between Hibernate merge() and update() methods?

What is the difference between Hibernate merge() and update() methods?

Ninja Asked on 17th September 2018 in Hibernate.
Add Comment
1 Answer(s)
Best answer

The update() method is used to save the object when the session object does not contain a persistent instance with the same identifier. The method will throw an exception if there is already a persistence instance associated with the session. The merge() method is used to merge the modifications without considering about the state of the session. It will just update without considering the session state.

This is explained in the code snippet below:

// In the first session
Student student = (Student) firstSession.load(Student.class, 1001);
student.setStudentGrade("A+");
.........
session.close();
// student is detached
Student studentTwo = (Student) secondSession.load(Student.class, 1001);
studentTwo.setStudentGrade("B");
..........
secondSession.update(student);
// Update here will it will throw an exception like org.hibernate.NonUniqueObjectException
secondSession.merge(student);
// Merge will simply update without concern about the session</p>

Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session.

Ninja Answered on 17th September 2018.
Add Comment