Difference Between get and load in Hibernate

In this post, we will discuss the difference between Session.get() and Session.load() method in Hibernate with an example.
Learn the Hibernate ORM framework at https://www.javaguides.net/p/hibernate-tutorial.html

Hibernate difference between Session.get() and Session.load() method

Session.load()

  • The Session.load() method will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, a proxy is an object with the given identifier value, its properties are not initialized yet, it just looks like a temporary fake object.
  • If no row found, it will throw an ObjectNotFoundException.

Session.get()

  • Session.get() method always hits the database and returns the real object, an object that represents the database row, not a proxy.
  • If no row found, it returns null.

Understanding with Examples

Let's understand the difference between Session.get() and Session.load() method with an example.
In the following example, we are using Session.get() and Session.load() method retrieve the data from the database:
public static void main(String[] args) {
    try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {

        // get the student entity using id
        Student student1 = session.get(Student.class, new Long(1));
        System.out.println("Student get called");
        System.out.println(student1.getId());
        System.out.println(student1.getLastName());
        System.out.println(student1.getEmail());

        // load student entity by id
        Student student2 = session.load(Student.class, new Long(2));
        System.out.println("Student load called");
        System.out.println(student2.getId());
        System.out.println(student2.getLastName());
        System.out.println(student2.getEmail());

    } catch (Exception e) {
        e.printStackTrace();
    }
}
Output:
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
Student get called
1
Fadatare
prabhas@gmail.com
Student load called
2
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
stark
tony@gmail.com
From the output, it’s clear that Session.get() returns the object by fetching it from a database or from hibernate cache whereas Session.load() just returns the reference of an object that might not actually exist, it loads the data from database or cache only when you access other properties of the object.
Now let’s try to fetch data that doesn’t exist in the database.
public static void main(String[] args) {
    try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {

        // get the student entity using id
        Student student1 = session.get(Student.class, new Long(3));
        System.out.println(student1);
        if (student1 != null) {
            System.out.println("Student get called");
            System.out.println(student1.getId());
            System.out.println(student1.getLastName());
            System.out.println(student1.getEmail());
        }


        // load student entity by id
        Student student2 = session.load(Student.class, new Long(4));

        if (student2 != null) {
            System.out.println("Student load called");
            System.out.println(student2.getId());
            System.out.println(student2.getLastName());
            System.out.println(student2.getEmail());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
Output:
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
null
Student load called
4
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [net.javaguides.hibernate.tutorial.entity.Student#4]
 at org.hibernate.boot.internal.StandardEntityNotFoundDelegate.handleEntityNotFound(StandardEntityNotFoundDelegate.java:28)
 at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:285)
 at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:180)
 at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:309)
 at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45)
 at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95)
 at net.javaguides.hibernate.tutorial.entity.Student$HibernateProxy$5eCbY0AD.getLastName(Unknown Source)
 at net.javaguides.hibernate.tutorial.Test.main(Test.java:33)
Look at the output closely, when we use Session.get() to retrieve data that doesn’t exist, it returns null. That makes sense because it tries to load the data as soon as it’s called.
With Session.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 if there is no record found with the given identifier.

Summary of Session.get() and Session.load() method

  • Session.get() loads the data as soon as it’s called whereas Session.load() returns a proxy object and loads data only when it’s actually required, so load() is better because it supports lazy loading.
  • Since Session.load() throws an exception when data is not found, we should use it only when we know data exists.
  • We should use Session.get() when we want to make sure data exists in the database.

Video

The below video explained the difference between get() and load() method in Hibernate with a complete coding example:

Related Posts

Comments