Pages Navigation Menu

Coding is much easier than you think

Different Between Session.Get() and Session.Load() in Hibernate


 
Often times, you will notice Hibernate developers mix use of session.get() and session load()
 
At first look both get() and load() seems similar because both of them fetch the data from database, however there are few differences between them, let’s look at those difference with simple example.
 

package util;

import entity.StudentEntity;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class GetVsLoad {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();
	
		// Get Example
		System.out.println("Student get called");

		StudentEntity student1 = (StudentEntity) session.get(StudentEntity.class, 1);
		System.out.println("Student ID="+ student1.getId());
		System.out.println("Student Get Details - " + student1 + "\n");

		// load Example
		System.out.println("Student load called");
		StudentEntity student2 = (StudentEntity) session.load(StudentEntity.class, 2);
		System.out.println("Student ID="+ student2.getId());
		System.out.println("Student load Details - " + student2 + "\n");

		// Close resources
		session.close();
		sf.close();
	}
}

 

 
From the output it’s clear that get() returns the object by fetching it from database whereas load() method will not hit the database (no select statement in output before printing ID) to retrieve the StudentEntity object, it will return a StudentEntity proxy object – a fake object created by hibernate with given identifier value(ID = 2).
 
In the above example we have called StudentEntity student2 = (StudentEntity) session.load(StudentEntity.class, 2); So here hibernate will create one fake StudentEntity object in the memory with id 2, but the other properties of StudentEntity class will not be initialized.
 
This method loads the data from database only when we try to access other properties of the StudentEntity object(Ex:- name, department, college). In the above example the DB hit takes place only after we try to call other member variable of StudentEntity object.
 

Now let’s try to fetch data that doesn’t exists in the database

 
Get Example
 

// Get Example
try {
	System.out.println("Session.get example");
	StudentEntity std = (StudentEntity) session.get(StudentEntity.class, 100);

	if (std == null) {
	System.out.println("Student Details not Found !! ");
	}
	else
	{
		System.out.println("Student Details Found !! ");
		System.out.println("Student GET ID="+ std.getId());
		System.out.println("Student Get Details - " + std + "\n");
	}
} catch (Exception e) {
	e.printStackTrace();
}

 
Load Example
 

// load Example
try {
	System.out.println("\nSession.load example");
	StudentEntity std2 = (StudentEntity) session.load(StudentEntity.class, 100);

	if (std2 == null) {
		System.out.println("Student Details not Found !! ");
	}
	else
	{
		System.out.println("Student Details Found !! ");
		System.out.println("Student LOAD ID="+ std2.getId());
		System.out.println("Student load Details - " + std2 + "\n");
	}
	
} catch (Exception e) {
	e.printStackTrace();
}

 
Above code produces following output.
 

 
In the above program when we use get() to retrieve data that doesn’t exists, it returns null. That makes sense because it try to load the data as soon as it’s called.
 
But With load(), we are able to print the ID; but as soon as we try to access other fields, it fires database query and throws org.hibernate.ObjectNotFoundException when there is no record found with the given identifier.
 
Another must read
Hibernate Eager vs Lazy Fetch Type
 

Special cases

 
If get(StudentEntity.class, 1) is called first and later again load(StudentEntity.class, 1) is called and if the record with primary key 1 exists, the s1 in the both the cases contains a real object. Why? We know get() method returns a StudentEntity object and load() returns s proxy object. With get(), a real object exists in the cache memory, the same object is returned to load() also.
If the reverse happens? If load() is called first and then get()? In both cases, s1 contains a proxy object because first load() returns a proxy and remains in the cache memory.
 

Summary

  • get() loads the data from database as soon as it’s called whereas load() returns a proxy object and loads data only from database when it’s actually required, so load() is better because it support lazy loading.
  • Since load() throws exception when data is not found, we should use it only when we know data exists.
  • We should not use load method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.
  • Both methods are used to retrieve only one Java object (record) from the database (for multiple records, we have, list() and iterate() methods).