Newsletter |
Difference Between Merge And Update Methods In Hibernate
Hibernate » on Sep 12, 2011 { 86 Comments } By Sivateja
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
------ ----- 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);
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 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
Hope you are clear…, actually update and merge methods will come into picture when ever we loaded the same object again and again into the database, like above.
You Might Also Like
::. About the Author .:: | ||
Comments
86 Responses to “Difference Between Merge And Update Methods In Hibernate”
Nice explanation i m surprise there is no comment for this this explanation cleat most of my doubt Thanx
@Sanket
You bet :-), thanks for your feedback on this.
Your’s explanation is like flow of river in calm state.I am glad to see your site here from your code.
@Jaffar
Thanks much 🙂 Glad to hear your feedback.
Its fabulous and great way of explaining things, I just love it.
I was always confused with these two methods but your way of explanation is simply awesome. Now I will never forget the difference. Thanks !!
@Rajesh,@Harish
I am really happy that it’s helped you friends 🙂 thanks for your time in giving this feedback.
Your explanation was tooo good
great explanation, thank you so much….
hi java4s team ,
you have given very excellent explaination , i got it clearly .
thanks a lot …
Thankx a lot for providing this and happy with your explanation
simple and straight…
simple and powerful example. thanks a lot
its well explained loving it
you xplanation is powerful so much, i think i m now java professional ::D thank u for explanetion also do u know dynamic-update? is good for scaling webapp? 8) lol
Hi ,
I am reffering to the above comments about the code explaination:
“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”
If we call merge() method instead of update also some Exception will occur, And in the second session we can again use the session2.update(s1) instead of session2.merge(s1) ?? isn’t it ?? Then what is the basic difference that where to use update and where to use merge ?? …..
Kindly clarify …..
Thanks in advance
Navin
Hi ,
if you are going to use session2.update(s1) you will get following exception
Exception in thread "main" org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.sumit.hiberanate.dto.Student#101]
at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:618)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:301)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:244)
at org.hibernate.event.internal.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireUpdate(SessionImpl.java:739)
at org.hibernate.internal.SessionImpl.update(SessionImpl.java:731)
at org.hibernate.internal.SessionImpl.update(SessionImpl.java:726)
yes same question i have please reply to Navin query .
Great explanation. I used to always confuse read and confused again but this explanation has cleared my all doubts. Explanation is friendly, easy to understand and direct not like typical examples found in books, tutorials that server nothing.
Hey Navin might be helpful
Sivateja has explained very well
But if you wanted in depth, try to look at this article
http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/
Generally we refer more than one site for our doubts, with this explanation no need of that.. TQ Siva….
clearing concepts with simplicity! Thanks…….:)
I am sorry. I am not happy with this explanation .
My question is what is the need of loading s2 if we had to update s1 in the second session. This is intensionally done to throw exception. Give me a real senario when such things happen.I can’t find any.
Secondly if merge() method is enough to do the change in object what is the need of update()? I would prefer mege() always instead of update().
Why the update() method is there?
what is the difference between save and persistence
the major difference between update and merge is that update cannot be used when the same object exists in the session.
Example :-
Student current = (Student)session.get(Student.class, new Integer(1));
System.out.println(“before merge ” + current.getName());
Student changed = new Student();
changed.setId(1);
changed.setName(“Changed new Name”);
// session.update(changed); // Cannot Use Update Since same object (Student) with Id 1 already exists
session.merge(changed); // merge will work fine and the name will get changed.
System.out.println(“after merge ” + current.getName()); // here current will now print the latest changed value since when the merge occurrs the one loaded in session is changed
Usefull. Thanks!
Got cleared
hey navin
i am completely agree with your explanation and you are right it will throw an exception..
The main difference between update and merge is ..when we call session.upadate() in session2 where object become persistence object from deacted object it looks for any update before and after session2.update then save it in dataBase but when you call session.Merge() it look at the update before the session.merge() stmt it doesn’t take care of stmt after session.merge() as session.update take care and update the dataBase..sorry if i am wrong
Explain about Fetching Strategies?
Article doesn’t explain difference between merge and update? Explanation from Sumeet Chopra in the comments session is better. Thanks.
Amazing sir..
clear cut explanation.
Nicely explained.
Very nice explanation. Thanks 🙂
Merge – First fetches the entity then does update.
Update – Updates the entity directly.
In both the cases it doesnot matter if entity already exists in the session or not.
Nice explanation. Thank you.
when iam starting a tomcat server in eclipse, it started but browser will display an error like “requested resource is not found” even for admin console also.
Doubt!!!!After loading S2 you are not doing anything with this object. You are just merging the S1 object with session2. What is going inside hibernate? How hibernate executing the queries?
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
i m not understand what is the requirement of this code
can you explain me pls
Great.Very good explanation.Thank you…
Amazing explanation.Thank you very much
Amazing sir..
clear cut explanation.
Great Nice Explanation…
Great explanation … Thank u
wonderful explanation. Amazing sir……
I am not happy with ur answer. I have same question as Navin.
Hi ,
I am reffering to the above comments about the code explaination:
“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”
If we call merge() method instead of update also some Exception will occur, And in the second session we can again use the session2.update(s1) instead of session2.merge(s1) ?? isn’t it ?? Then what is the basic difference that where to use update and where to use merge ?? …..
Kindly clarify …..
Thanks in advance
Navin
Hello Guest,
Let me try to help you out here.
The difference comes into the picture when we load the object of same identifier in two different sessions and try to update first object (which is detached) in the second session , Hibernate will throw an exception as below –
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:<Your entity name>
So, if you replace the line with session2.update(s1), you will get above exception.
So, to avoid such exception, merge() method comes into the picture.
I hope you get some help from my explanation.
Hi,
Nice explanation but still it's creating some doubts to me.
1. why we need line no#15.
2. if we do not write line no# 15, can we do session2.update(s1);
Thanks,
Saurabh
It’s really nice.
If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.
Nice explanation…thank you
Hi Siva teja,
Way of explanation is really good!!!
I’m not happy with this answer..
Hi Sir,
Really , you have provided extremely awesome explanation of update and merge methods.
Thanks a lot !!!!
nice explanation:)
Thank you very much for your wonderful explanations and tutorials.
Hey, really nice explanation !!! 🙂
Thanks for thinking about JAVA4S and making it alive and updated !!!
explanation is good . but more clarification needed
NIce Explanation.very good
Good Exeplection nice
your explanation is excellent sir
Thanks, nice explanation
U explained in a awesome way … Thanx fo that ..
Too good ,very simple explanation.keep it up
Sorry, I’m not happy with your ans bro.. I’m having the same doubt as Navin. What the object s2 doing here ?
Nice explanation,I want just add one point here.
Session2 can use the update method if we load the same identifier student object with load method except get method
Very good explanation,keep it up…
Great explanation…simple with clarity
nice explanation clear and very helpful to unbderstand
Your cool and clear way of explanation I liked very much…Thnx
very nice explanation
Very Nice Explanation.
Amazing explanation.
Nice Explanation.
why below code not giving error.
I am loaded the object with session1 and updated with session2
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
System.out.println("About to fetch Record !!");
Employee emp = (Employee) session.get(Employee.class, 7);
session.close();
emp.setEmpSal(500);
Session session2 = factory.openSession();
session2.beginTransaction();
session2.update(emp);
session2.beginTransaction().commit();
session2.close();
Ok Very well Explained But,
But my doubt is can we able to use two diffrence sessions at once in real time
can u pls give any real time example for diffrence between update and merge
By A Student
Thanks a lot 🙂
Clear cut explanation…….Thank you
Nice explanation but I have a query. When we do update & merge in the second session. Does it check cache?
Because When we call get() at that time it goes to cache first so Does it happens same with update() & merge().
Great explanation
very nice explanation it help me alot….clear my all doubt….thnx:-)
This explanationtion doesn't clear anything except explaining it with an example . None of the explanation is clear. This doesnt answer why should some one use merge? In the example , what is the need to loading s2 when doing changes in S1 is enough. Hope one day I will get the answer and put here.
How update method is used to convert a Detached object to persistent object when it throws an error while trying to update a detached object(the object is detached if the session is closed). The point is that update method can only be used on an object in an active session.
This example is not giving modified value in database.
Object o1 = session2.get(Student.class, new Integer(102));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();
session2.merge(s1);
wt will happen when sesssion has different identifier and we call merger other object??
Object o1 = session2.get(Student.class, new Integer(102));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();
session2.merge(s1);
wt will happen when session has different identifier but we are trying to merger other object.
Good explanation in short way..
Hats off you Java4s…