Difference between get and load method in Hibernate

The difference between get and load method in Hibernate tutorial will show you how to use two method in different circumstances. This tutorial is a one of the most popular question asked in Hibernate and Spring interviews.

Hibernate Session provide different methods to fetch data from database. Two of them are get() and load() method. Both of them look quite similar to each other however there are few difference between load and get() method that can affect performance of application. Let’s look at them with below examples.

Other interesting posts you may like

In this difference between get and load method in Hibernate tutorial, we will create the final project directory structure like below:

difference between get and load method in Hibernate

Let’s try to fetch data using get() and load() method:

Run above main class and it produces following output.

As you see on the above output, it’s clear that get() method returns the object by fetching it from database.
While load() method just returns the reference of an object. Only when we access properties of the object it just loads the data from database. It is reason why the load() method can return reference of object that might not actually exists.

Let’s try to fecth data that doesn’t exists with below examples:

Run above main class and it produces following output:

Look into the above output. The get() method returns null. This is evident it try to fetch the data as soon as it’s executed.

While the load() method just try to load object since we print the id of that object. In this case, we try to fetch data that doesn’t exists so that it throws org.hibernate.ObjectNotFoundException.

Conclusion

Based on the above examples we have difference between get and load method in Hibernate like below:

The get() method fetches data as soon as it’s executed while the load() method returns a proxy object and fetches only data when object properties is required.
So that the load() method gets better performance because it support lazy loading.
Whe should use the load() method only when we know data exists because it throws exception when data is not found.
In case we want to make sure data exists we should use the get() method.

In short, you should understand the differential in between, and decide which method is best fix in your application. That’s all for the difference between get and load method in Hibernate tutorial.

Download complete source code, please click link below

HibernateSessionExample-1.zip (50 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons