load() and get() methods of Hibernate Session

Hibernate Session provides two methods to access the object (session.get() & session.load()). Both looks like same but there are differences between load () and get () methods. Let’s have a look at those.

load():

  • load() method throws hibernate.ObjectNotFoundException (which is Un-checked exception) if object not found in cache as well as in database.
  • load() method is lazy loading i.e. when you call session.load(Class,identifier) method, it will return Proxy object but not entity
  • Use load() method when you are sure that the object exists in database.
  • load() method is equivalent to getReference() method of JPA.
  • Since load() method returns proxy object, so it is not fully available in any future detached state. Detached state means Object is not associated with Session, but present in Database. So if you are not working with detached objects load() or getReference() methods can be use to have better performance.

get():

  • get() method returns NULL , if object is not found in cache as well as in database.
  • get() method is early loading e. when you call session.get(Class,identifier) method, it will hit the database immediately ,loads the entity object and returns the entity object.
  • Use get() method if you are not sure that the object exists in database.
  • It is equivalent to EntityManager.find() method of JPA.
  • Since get() returns a fully initialized object, so it is fully available in any future detached state.

How to call load() method:

How to call get() method:

When to use get() and load():

 1) Requirement: If object is present you need to implement some logic otherwise you need to implement some other logic.

   get(): if object is not returned with get method, it returns null, so we can implement above requirement as below.       

   load(): If object is not returned it throws Exception, so we cannot use load() method for this requirement.

So, we need to use get() method for the above requirement.

2)  Use load() method if your code doesn’t access any method other than the identifier. It just returns the proxy object.   

Posted in hibernate and tagged , , , .

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="">