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