Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database.

Session.get()

The session.get() method is used to fetch a persistent object of the given class with the given identifier. When we use the session.get() method, it will directly hit the database and return the real object from the database. If no persistent object found in the database, it returns null.

There are four get() methods available in Session interface with different parameters:

  • get(Class class, Serializable id)
  • get(Class class, Serializable id, LockOptions lockOptions)
  • get(String entityName, Serializable id)
  • get(String entityName, Serializable id, LockOptions lockoptions)

All of the above methods perform the same functions.

How to use session.get() method

Session session = SessionFactory.getCurrentSession();
Employee employee = (Employee) session.get(Employee.class, 1); 

In the above code, session.get() method is fetching an object of Employee class with the given identifier 1.

Session.load()

The session.load() method returns a 'proxy' object instead of a real object, without hitting the database. A proxy is an object with the given identifier value, and its properties are not initialized. It acts as a temporary object. If the persistent object is not found, it will throw an exception called ObjectNotFoundException.

There are four load() methods available in the Session interface with different parameters:

  • load(Class theClass, Serializable id)
  • load(Class theClass, Serializable id, LockOptions lockOptions)
  • load(String entityName, Serializable id)
  • load(String entityName, Serializable id, LockOptions lockOptions)

All of the above methods perform the same functions.

How to use session.load() method

Session session = SessionFactory.getCurrentSession();
Employee employee = (Employee) session.load(Employee.class, 1); 

In the above code, session.load() is fetching an object of Employee class with the given identifier 1.

Difference between get() and load()

            Parameter                        Get                      Load
Use If we are not confident about the presence of the object, we use the get() method. If we are confident about the existence of the object, we can use the load() method.
Database hit The get() method always hits the database when called. The load() method does not always hit the database when called.
Object not found The get() method will return null if the object is not found in the database. The load() method will throw an exception (ObjectNotFoundException) if the object is not found.
Object retrieval This method will return a real object. This method will return a proxy object in place of a real object.
Loading type The get() method uses Eager Loading. The load() method uses Lazy Loading.