Pages Navigation Menu

Coding is much easier than you think

Difference Between Update and Merge methods In Hibernate

 
update merge in hibernate
 
Often times, you will notice Hibernate developers mix use of session.update() and session.merge()

At first look both update() and merge() methods seems similar because both of them are used to convert the object which is in detached state into persistence state, but the major difference between update and merge is that update method cannot be used when the same object exists in the session. Let’s look at those difference with simple example.
 
Example :-
 

	Student current = (Student)session.get(Student.class, 100);
	System.out.println("Before merge: " + current.getName());
	Student changed = new Student();
	changed.setId(100);
	changed.setName("Changed new Name");
	// session.update(changed); // Throws NonUniqueObjectException
	session.merge(changed);
	System.out.println("After merge: " + current.getName());

 

Explanation

 
In the above program I have loaded a Student object of ID ‘100’ at line no 1. After that I have created a new Student object ‘changed’ with same ID ‘100’. Now if I try to call update method on this ‘changed’ object, then Hibernate will through a NonUniqueObjectException, because the same object (Student) with Id ‘100’ already exists in session.
 
Now at line no ‘7’, I have called session.merge(changed); this merge() 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.
 
Done and done! So there you have it, you now know the exact difference between merge() and update() method in Hibernate framework and actually the usage of merge() methods will come into picture when ever we try to load the same object again and again into the database.
 

Other Hibernate tutorial from our Blog

 

4 Comments

  1. Thanks very good and straight example without any unnecessary formalities

  2. Got it… Nice explanation

  3. Awesome explanation,, short & to the point but serves it purpose effectively.. Really helpfull.