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 69, 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.

Folks i have been changed the values in the source code

Difference-between-merge-and-update-methods

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

86 Responses to “Difference Between Merge And Update Methods In Hibernate”
  1. Sanket says:

    Nice explanation i m surprise there is no comment for this this explanation cleat most of my doubt Thanx

  2. Java4s says:

    @Sanket

    You bet :-), thanks for your feedback on this.

  3. jaffar says:

    Your’s explanation is like flow of river in calm state.I am glad to see your site here from your code.

  4. Java4s says:

    @Jaffar

    Thanks much 🙂 Glad to hear your feedback.

  5. Rajesh says:

    Its fabulous and great way of explaining things, I just love it.

  6. Harish says:

    I was always confused with these two methods but your way of explanation is simply awesome. Now I will never forget the difference. Thanks !!

  7. Java4s says:

    @Rajesh,@Harish

    I am really happy that it’s helped you friends 🙂 thanks for your time in giving this feedback.

  8. Nagarjuna says:

    Your explanation was tooo good

  9. Amey says:

    great explanation, thank you so much….

  10. hi java4s team ,
    you have given very excellent explaination , i got it clearly .

    thanks a lot …

  11. srinivas says:

    Thankx a lot for providing this and happy with your explanation

  12. sudhakar says:

    simple and straight…

  13. chinna says:

    simple and powerful example. thanks a lot

  14. amar says:

    its well explained loving it

  15. Sharif says:

    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

  16. NAVIN says:

    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

    • sumit kumar says:

      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)

  17. raghu says:

    yes same question i have please reply to Navin query .

  18. 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.

  19. 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/

  20. karthik says:

    Generally we refer more than one site for our doubts, with this explanation no need of that.. TQ Siva….

  21. pankaj says:

    clearing concepts with simplicity! Thanks…….:)

  22. Debasis says:

    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?

  23. mani says:

    what is the difference between save and persistence

  24. 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

  25. uj says:

    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

  26. ashokkumar says:

    Explain about Fetching Strategies?

  27. Murali KB says:

    Article doesn’t explain difference between merge and update? Explanation from Sumeet Chopra in the comments session is better. Thanks.

  28. divya says:

    Amazing sir..
    clear cut explanation.

  29. Satish says:

    Very nice explanation. Thanks 🙂

  30. Sujata says:

    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.

  31. Nice explanation. Thank you.

  32. Vishnu says:

    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.

  33. 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?

  34. tarkesh says:

    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

  35. samba says:

    Great.Very good explanation.Thank you…

  36. Selva says:

    Amazing explanation.Thank you very much

  37. samir says:

    Amazing sir..
    clear cut explanation.

  38. Ramakrishna says:

    Great Nice Explanation…

  39. Atchaiah says:

    Great explanation … Thank u

  40. shanmugam says:

    wonderful explanation. Amazing sir……

  41. Guest says:

    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

    • Swapnil N. says:

      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.

      • Saurabh says:

        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

  42. shankar prasad says:

    It’s really nice.

  43. kola says:

    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.

  44. channu says:

    Nice explanation…thank you

  45. sathish says:

    Hi Siva teja,

    Way of explanation is really good!!!

  46. Tarun says:

    I’m not happy with this answer..

  47. Raju says:

    Hi Sir,

    Really , you have provided extremely awesome explanation of update and merge methods.

    Thanks a lot !!!!

  48. eliyasreddy says:

    nice explanation:)

  49. Nimai says:

    Thank you very much for your wonderful explanations and tutorials.

  50. Buddys_Cafe says:

    Hey, really nice explanation !!! 🙂

    Thanks for thinking about JAVA4S and making it alive and updated !!!

  51. yuvi says:

    explanation is good . but more clarification needed

  52. venkat says:

    NIce Explanation.very good

  53. vijay kumar says:

    Good Exeplection nice

  54. sivareddy says:

    your explanation is excellent sir

  55. Binh Thanh Nguyen says:

    Thanks, nice explanation

  56. Prasad says:

    U explained in a awesome way … Thanx fo that ..

  57. poonam says:

    Too good ,very simple explanation.keep it up

  58. Sai Krishna says:

    Sorry, I’m not happy with your ans bro.. I’m having the same doubt as Navin. What the object s2 doing here ?

  59. Vinod says:

    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

  60. Ramakrishna says:

    Very good explanation,keep it up…

  61. P Mukherjee says:

    Great explanation…simple with clarity

  62. bikash dash says:

    nice explanation clear and very helpful to unbderstand

  63. praphulla says:

    Your cool and clear way of explanation I liked very much…Thnx

  64. Mehraj Malik says:

    Very Nice Explanation.

  65. PD says:

    Amazing explanation.

  66. Ajit Paswan says:

    Nice Explanation.

  67. Ramesh says:

    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();

  68. Pavan says:

    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

  69. Rahul says:

    Thanks a lot 🙂

  70. Sonu Singh says:

    Clear cut explanation…….Thank you

  71. Rathod says:

    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().

  72. Sajid says:

    Great explanation

  73. shobhit says:

    very nice explanation it help me alot….clear my all doubt….thnx:-)

  74. Deb says:

    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.

  75. Steven says:

    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.

  76. shivani says:

    This example is not giving modified value in database.

  77. amit says:

    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??

  78. amit says:

    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.

  79. Manjappa says:

    Good explanation in short way..
    Hats off you Java4s…

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.