Difference between update vs merge in Hibernate example

By | 2018-09-24T11:58:44+00:00 October 7th, 2015|Hibernate|7 Comments

In this tutorial we will see the most important topic in hibernate, differences between update() vs merge() methods.

As we discussed in the previous tutorials, hibernate object has different states that are transient, persistent and detached.

Basically, the both update() and merge() methods are used to change the state of an object. That means we can call either update() or merge() to transfer an object from detached state to persistent state.

A detached state object can be made persist by reattaching to a session. If the previous session is already been closed, it is also possible to create a new session and can attach to that session.

To reattach we can use update() or merge() methods. Both are doing the same functionality, but there are few differences internally.

Difference between update vs merge :

When we call update() method on session, if that session doesn’t contains same object (provided in update())  in cache then update() method successfully executed and the object been converted detached state to persistent state.

Recommended : Different object states in Hibernate

How update() works ?:

When we call update() method on any object, it intern checks, if that object is already existed in session cache or not — if currently updating object is already there in session cache then it throws an exception called NonUniqueObjectException, otherwise it will update the object.

Example of update() :

Existing database table is like below, I am going to update the values in student table using the update() method :

Hibernate Update Example

UpdateExample.java

UpdateExample.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UpdateExample {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();

        Student student2 = (Student) session.get(Student.class, 111);
        session.close();

//          Here student object is in detached state
        student2.setName("chandrashekhar");

//        reattaching to session
        Session session2 = factory.openSession();
        Transaction tx = session2.beginTransaction();
        session2.update(student2);
        tx.commit();

    }
}

Output :

hibernate update output

Database :

Hibernate update Database

Example 2 :

When we call update() method, if already a session cache containing the same object then the update() method throws an exception called NonUniqueObjectException.

HibernateUpdateExample.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUpdateExample {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();

        Student student = (Student) session.get(Student.class, 111);
        session.close();

//          Here student object is in detached state
        student.setName("chandrashekhar");

//        reattaching to session
        Session session2 = factory.openSession();
        Student student2 = session2.get(Student.class, 111);
        Transaction tx = session2.beginTransaction();

        session2.update(student);
        tx.commit();

    }
}

Output :

Console
Exception in thread "main" org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.onlinetutorialspoint.pojo.Student#111]

On the above example student2 object with Id ‘111’  is already available in session2, if we try to update with the old object (student object) then update() will throw NonUniqueObjectException.

How merge() works ?

Like update() method merge is also used to transfer an object from detached stated to persistent state.

If we call merge() method, then it verifies whether the same object has existed in the session cache or not. If the object has existed in the cache then the current changes are copied in to the cache, otherwise, it will load the values to cache.

Example :

MergeExample.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class MergeExample {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();

        Student student = (Student) session.get(Student.class, 111);
        session.close();

//          Here student object is in detached state
        student.setName("John");

//        reattaching to session 
        Session session2 = factory.openSession();
        Student student2 = session2.get(Student.class, 111);
        Transaction tx = session2.beginTransaction();

        session2.merge(student);
        tx.commit();

    }
}

Output :

merge exampleUpdate vs merge :

update vs merge in hibernateWhen we call update() method, if the object already existed in cache update() method will throw exception whereas merge() method copies the changes in to cache.

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

7 Comments

  1. gauravpant2934@gmail.com'
    Gaurav Pant September 23, 2016 at 10:26 am - Reply

    Best explanation I have ever read..
    Very clearly explained the difference.

  2. lkarthiks15@gmail.com'
    Karthi December 3, 2016 at 3:22 am - Reply

    Very detailed and neat explanation. I can able to understand concepts clearly. Thanks for your wonderful explanation.

  3. vsl.k.th@gmail.com'
    vishal thakur January 24, 2017 at 8:20 am - Reply

    best explanation..it resolve all of my confusion.

  4. mansharma90@gmail.com'
    Mandeep June 1, 2017 at 5:49 pm - Reply

    Hi I have exeuted this code for both update and merge. but in both of the cases record is getting updated?

    Please explain?
    Session session=sessionFactory.openSession();
    Home Home2 = (Home) session.get(Home.class,new Long(25));
    System.out.println(“Home get obejct is “+Home2);
    session.close();

    // Here Home object is in detached state
    Home2.setName(“abc”);

    // reattaching to session
    Session session2 = sessionFactory.openSession();
    org.hibernate.Transaction tx = session2.beginTransaction();
    // session2.merge(Home2);
    session2.update(Home2);
    session2.flush();
    System.out.println();
    tx.commit();
    r

    • chandrashekhar June 4, 2017 at 6:46 am - Reply

      In reply to Mandeep.

      Hi Manideep,

      In your code,
      // reattaching to session
      Session session2 = sessionFactory.openSession();
      org.hibernate.Transaction tx = session2.beginTransaction();

      you are updating the same object on different sessions, there is no much difference on this.

      For more information you can see the difference between load() and get() methods in hibernate.

  5. tauhid9210@gmail.com'
    tauhid May 10, 2018 at 12:00 pm - Reply

    nice explanation …. thanks

  6. shrijasodhi7709@gmail.com'
    shrija September 18, 2018 at 11:58 am - Reply

    I really liked your article , your article is very
    petrified me in the learning process and provide
    additional knowledge to me , maybe I can learn
    more from you, thank you for sharing this

Leave A Comment