Difference between update vs merge in Hibernate example

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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
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.
The existing database table is like below; I am going to update the values in the student table using the update() method :
 
 
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 :
 
 
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.
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.
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 :
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 :
 
 
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 🙂

Different types of Object States in Hibernate
Hibernate cache first level example
Hibernate session differences between load() and get()
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Singleton Hibernate SessionFactory Example
Hibernate Filter Example Xml Configuration
Hibernate Interceptor Example
Basic Hibernate Example with XML Configuration
Hibernate Composite Key Mapping Example
Top 7 Interview Questions in Hibernate
Hibernate 4 Example with Annotations Mysql
hibernate update query example
HQL update, delete Query Example
Difference between b++ and b=b+1

Different types of Object States in Hibernate
Hibernate cache first level example
Hibernate session differences between load() and get()
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Singleton Hibernate SessionFactory Example
Hibernate Filter Example Xml Configuration
Hibernate Interceptor Example
Basic Hibernate Example with XML Configuration
Hibernate Composite Key Mapping Example
Top 7 Interview Questions in Hibernate
Hibernate 4 Example with Annotations Mysql
hibernate update query example
HQL update, delete Query Example
Difference between b++ and b=b+1






Gaurav Pant
September 23, 2016 at 10:26 am - Reply 

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









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.









vishal thakur
January 24, 2017 at 8:20 am - Reply 

best explanation..it resolve all of my confusion.









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.











tauhid
May 10, 2018 at 12:00 pm - Reply 

nice explanation .... thanks









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









Prahalad
December 13, 2018 at 12:37 pm - Reply 

Nice Explanation









Eshwar
September 14, 2021 at 8:52 am - Reply 

Very clearly explained the difference. Thank you a lot










Gaurav Pant
September 23, 2016 at 10:26 am - Reply 

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




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





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.




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





vishal thakur
January 24, 2017 at 8:20 am - Reply 

best explanation..it resolve all of my confusion.




best explanation..it resolve all of my confusion.





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.






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.




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.





tauhid
May 10, 2018 at 12:00 pm - Reply 

nice explanation .... thanks




nice explanation .... thanks





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




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





Prahalad
December 13, 2018 at 12:37 pm - Reply 

Nice Explanation




Nice Explanation





Eshwar
September 14, 2021 at 8:52 am - Reply 

Very clearly explained the difference. Thank you a lot




Very clearly explained the difference. Thank you a lot
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache