Hibernate

Difference Between get() and load() Methods in Hibernate

In hibernate session there are two methods for retrieving object from database one is get() and other load() method. These two methods have been used in the different situations but both are from Session interface and we will call them as session.get() & session.load(). This is one of the famous hibernate interview questions. Let’s see differences between them with example.

Sample Example Hibernate Application for get() and load() methods

Consider a Employee class having 3 properties empid, empName, address.

Example of session.get():

package com.dineshonjava.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.sdnext.hibernate.tutorial.dto.Employee;


public class HibernateTestDemo {
 
 private static SessionFactory sessionFactory = createSessionFactory();
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  Employee employee = null;
  Session session = sessionFactory.openSession();
  Transaction transaction = session.beginTransaction();
  transaction.begin();
  employee = (Employee) session.get(Employee.class, 1);
                //get employee object with id 1 
  System.out.println(employee);
                //update employee address of retrieved object, it immediately update to DB because of get method retrieved actual persistent object        
  employee.setAddress("Noida");
                //Here we have updated object  
  System.out.println(employee);

  transaction.commit();
  session.close();
  sessionFactory.close();
 }
 
 private static SessionFactory createSessionFactory() {
     if (sessionFactory == null) {
         StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
         Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
         sessionFactory = metaData.getSessionFactoryBuilder().build();
     }
     return sessionFactory;
 }
}

Output on console:

......................................
.................................
Jan 31, 2017 10:42:58 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Jan 31, 2017 10:42:58 PM org.hibernate.boot.internal.SessionFactoryBuilderImpl$SessionFactoryOptionsStateStandardImpl 
WARN: Unrecognized hbm2ddl_auto value : create | update.  Supported values include create, create-drop, update, and validate.  Ignoring
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=?
Employee [empid=1, empname=Dinesh Rajput, address=New Delhi]
Employee [empid=1, empname=Dinesh Rajput, address=Noida]
Hibernate: update EMPLOYEE set ADDRESS=?, EMP_NAME=? where EMPID=?
......................
......................

Explanation:
Here when we call session.get() method hibernate will hit the database and returns the original object [ row ], that’s the reason it was generated a query when we update any value of this object. If suppose object of given id does not exist in data base then it return null instead throwing any exception let’s see as below console output.

......................................
.................................
WARN: Unrecognized hbm2ddl_auto value : create | update.  Supported values include create, create-drop, update, and validate.  Ignoring
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=?
null
......................
......................

Example of session.load():

package com.dineshonjava.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.sdnext.hibernate.tutorial.dto.Employee;


public class HibernateTestDemo {
 
 private static SessionFactory sessionFactory = createSessionFactory();
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  Employee employee = null;
  Session session = sessionFactory.openSession();
  Transaction transaction = session.beginTransaction();
  transaction.begin();
  employee = (Employee) session.load(Employee.class, 1);
                //get employee object with id 1 
  System.out.println(employee);
                //if object found then update employee address of retrieved the proxy object instead of original object i.e. it does not update to DB         
  employee.setAddress("Noida");
                transaction.commit();
  session.close();
  sessionFactory.close();
 }
 
 private static SessionFactory createSessionFactory() {
     if (sessionFactory == null) {
         StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
         Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
         sessionFactory = metaData.getSessionFactoryBuilder().build();
     }
     return sessionFactory;
 }
}


Output on console:

......................................
.................................
WARN: Unrecognized hbm2ddl_auto value : create | update.  Supported values include create, create-drop, update, and validate.  Ignoring
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=?
Employee [empid=1, empname=Dinesh Rajput, address=Noida]
......................
......................

Explanation:
When you call session.load() method, it will always return a “proxy” object, Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting the database, for example if we call session.load(Employee.class, 1) then hibernate will create one fake Employee object [row] in the memory with id 1, when we made change to property of object it didn’t update database because of proxy object. So finally we came to know that session.load() will hit the database only when we start retrieving the object (row) values. In case of given id object doesn’t exist in DB then this method will throw an Exception as below.

......................................
.................................
WARN: Unrecognized hbm2ddl_auto value : create | update.  Supported values include create, create-drop, update, and validate.  Ignoring
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=?
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.sdnext.hibernate.tutorial.dto.Employee#4]
 at org.hibernate.boot.internal.StandardEntityNotFoundDelegate.handleEntityNotFound(StandardEntityNotFoundDelegate.java:28)
 at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:242)
 at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:159)
 at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266)
 at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68)
 at com.sdnext.hibernate.tutorial.dto.Employee_$$_jvstc72_0.toString(Employee_$$_jvstc72_0.java)
 at java.lang.String.valueOf(Unknown Source)
 at java.io.PrintStream.println(Unknown Source)
 at com.sdnext.hibernate.tutorial.HibernateTestDemo.main(HibernateTestDemo.java:34)
......................
......................

After discussion of this above example there are following difference we found as pointed below.

Session.load():

  • It will always return a “proxy” without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
  • load() method doesn’t hit the database.
  • If no row found , it will throws an ObjectNotFoundException.

Session.get():

  • It always hit the database and return the real object, an object that represent the database row, not proxy.
  • If no row found , it return null.
  • get() method always hit the database.
  • It returns real object not proxy.

 

Previous
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago