top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: What is the difference between update and merge method in hibernate?Explain with scenario based example?

0 votes
649 views
Java: What is the difference between update and merge method in hibernate?Explain with scenario based example?
posted Feb 29, 2016 by Dominic

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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.

-----------
-----------
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();

Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();

s1.setMarks(97);

Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();

session2.merge(s1);

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 be destroyed 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.

answer Mar 2, 2016 by Josita Sarwan
...