Difference between Session get and load in Hibernate

Hibernate Session provides two methods to retrieve object e.g. get() and load() both looked quite similar to each other but there are subtle difference between load and get method.

The major difference between two methods is:

  • get method will involve a database query if the record is not in the cache, and obtain a fully initialized object. However, load method can return a proxy object and only initialize the object or query the database when it is required. Since load method supports lazy loading, it may result in better performance.
  • load method throws exception if the data is not found while get method return a null object. Therefore, it is better to use load method when you know the data record is in the database

Let’s take a looks at some examples:

Case 1: database records are available

Output

Hibernate log

From the output and Hibernate log, we can see that get method will query database if the record is not in the cache, and obtain the object while load method can return a proxy object and only initialize the object or query the database when it is required.

Case 2: database records cannot be found

output

Conclusion

Hibernate Session get() method and load() method look similar, but there are difference between two methods. Load method uses lazy loading, and has better performance. However, if no record can be found it will throw exception when using load() method. As there is no best solution, you should choose which method based on your application.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">