Monday , October 23 2017
Home / Hibernate / Difference between update vs merge in Hibernate example

Difference between update vs merge in Hibernate example

What is the different between update and merge method in hibernate is one of the most frequently asked interview question. In previous tutorials we have discussed about differences between load() and get() methods. In this tutorial let us see about update() vs merge() methods in hibernate. And which method will use for which situation.

The both update()  and merge() methods are used to change the objects states in hibernate. We can call update() and merge() methods to transfer an object from detached state to persistent state.

A detached state object can be made persist by reattaching to a session. If previous session is closed then we can open a new session and we can reattach to a new 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 : Object States in Hibernate

How update() works ?:

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

Example :

Existing database table is like below, we need to update the values in student table using the update() method :

Hibernate Update ExampleStudent.pojo


package com.onlinetutorialspoint.pojo;

public class Student implements java.io.Serializable {

    private Integer id;
    private String name;
    private Integer rollNumber;

    public Student() {
    }

    public Student(Integer id, String name, Integer rollNumber) {
        this.id = id;
        this.name = name;
        this.rollNumber = rollNumber;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getRollNumber() {
        return this.rollNumber;
    }

    public void setRollNumber(Integer rollNumber) {
        this.rollNumber = rollNumber;
    }

}

Student.hbm.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class catalog="onlinetutorialspoint" name="com.onlinetutorialspoint.pojo.Student" table="student">
        <id name="id" type="java.lang.Integer">
            <column name="id"/>
        </id>
        <property name="name" type="string">
            <column length="50" name="name"/>
        </property>
        <property name="rollNumber" type="java.lang.Integer">
            <column name="rollnumber"/>
        </property>
    </class>
</hibernate-mapping>

Main class : 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 outputDatabase :

Hibernate update DatabaseExample 2 :

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


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 :
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 is existed in the cache or not. If the object is existed in the cache then changes are copied in to the cache. other wise it will load the values to cache. Hence it doesn’t throw any exception.

Example :


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 where as merge() method copies the changes in to cache.

Happy Learning 🙂

About chandrashekhar

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+ ,

Recommended

Hibernate Native SQL Query Example

In this tutorials, we are going to learn about Hibernate Native SQL with example. Hibernate …

5 comments

  1. gauravpant2934@gmail.com'

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

  2. lkarthiks15@gmail.com'

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

  3. vsl.k.th@gmail.com'

    best explanation..it resolve all of my confusion.

  4. mansharma90@gmail.com'

    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

Leave a Reply

Your email address will not be published. Required fields are marked *