In this tutorial we will see the most critical 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.

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 to persist by reattaching to a session. If the previous session has 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 the session, if that session doesn’t contain the same object (provided in the update())  in the 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() :

The existing database table is like below; I am going to update the values in the 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 lived in the cache, then the current changes are copied into 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 example

 

Update vs merge :

 

update vs merge in hibernate

When we call update() method, if the object already existed in cache update() method will throw an exception whereas merge() method copies the changes into the cache.

Happy Learning 🙂