get vs load in Hibernate

In Hibernate, the methods get() and load() methods are used to retrieve data from the database, but they have some key differences in how they operate. In this post, we will discuss the difference between the Session.get() and Session.load() methods in Hibernate with an example.
Learn the Hibernate ORM framework at Learn Hibernate Framework

Session get() Method

Return Value: If the object is not found, the get method returns null.

Database Query: It hits the database immediately when called and retrieves the values.

Proxy Creation: This does not create a proxy object. Fetches the real object from the database.

Performance: It might be slightly slower compared to load as it fetches the data right away.

Use Case: Use this when you're not sure whether the object exists or not, as it won't throw an exception if the object is not found.

Session load() Method

Return Value: If the object is not found, it will throw an ObjectNotFoundException.

Database Query: It doesn't hit the database immediately. Instead, it returns a proxy object, and the database is queried only when the properties of that object are accessed.

Proxy Creation: Creates a proxy object for the associated entity, providing a form of lazy initialization.

Performance: It might be faster if the object's properties are never accessed, as it avoids unnecessary database hits.

Use Case: Use this when you're certain the object exists, and you want to take advantage of lazy loading.

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() methods to 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
[email protected]
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
[email protected]
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 a database query and throws org.hibernate.ObjectNotFoundException if there is no record found with the given identifier.

Summary

Here's a table summarizing the key differences:
Feature get() Method load() Method
Return Value Returns null if not found Throws ObjectNotFoundException if not found
Database Query Immediate Lazy (on accessing properties)
Proxy Creation No Yes
Performance May be slower (immediate fetch) May be faster (lazy loading)
Use Case When object existence is uncertain When object existence is certain and lazy loading is desired

Related Posts

Comments