Both update() and merge() methods in hibernate are used to convert the object which is in detached state into persistence state. But there is little difference. Let us see which method will be used in what situation.
Let Us Take An Example
Explanation
- See from line numbers 6 – 9, we just loaded one object s1 into session1 cache and closed session1 at line number 9, so now object s1 in the session1 cache will bedestroyed as session1 cache will expires when ever we say session1.close()
- Now s1 object will be in some RAM location, not in the session1 cache
- here s1 is in detached state, and at line number 11 we modified that detached object s1, now if we call update() method then hibernate will throws an error, because we can update the object in the session only
- So we opened another session [session2] at line number 13, and again loaded the same student object from the database, but with name s2
- so in this session2, we called session2.merge(s1); now into s2 object s1 changes will be merged and saved into the database
http://www.simplecodestuffs.com/difference-between-update-and-merge-methods-in-hibernate/
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 :-
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.
No comments:
Post a Comment