Hibernate – load() vs get()

The main difference is:

  • if load() can’t find the object in the cache or database, an exception is thrown.
    The load() method never returns null.
  • The get() method returns null if the object can’t be found.
  • Other difference is that the load() method may return a proxy instead of a real instance but get() never does return proxy.

ie: If object is not found, load() method will throw exception but get() won’t throw exception.

To elaborate the things,

  1. When get() method is called, it will directly hit the database, fetch the result and return. If no matching fields are found, it will gladly return null.
  2. But when load() executes, firstly it will search the cache for required object. If found, all is well.
    But if object is not found in cache, load() method will return a proxy.
    You can consider this proxy as a shortcut for database query execution.
    Remember, no database hit is made yet.
    Now when you actually access the object the proxy will be traced and database hit will be made.

Let’s consider a simple example.

User user=(User)session.load(User.class, new Long(1));//Line 1

System.out.println(user.getPassword());//Line 2
  • In the above code : If User object with primary key 1 is not available in session, the load() method will set a proxy for the database at Line 1. Now when actual value of the ‘user’ object is called, i.e. line 2, the proxy will be traced and the database will be hit.

 

see example here :

    1. get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading [Read more below to understand importance of lazy loading here]
    2. Since load() throws exception when data is not found, we should use it only when we know data exists.
    3. We should use get() when we want to make sure data exists in the database.

      ——-

To understood get vs load read the below post, which explains why load() is better than get(),  at times when lazy loading is really required.
–  https: //www.mkyong.com/hibernate/different-between-session-get-and-session-load/

References:

http://stackoverflow.com/questions/6924799/understanding-session-get-vs-session-load-method-in-hibernate

http: //www.journaldev.com/3472/hibernate-session-get-vs-load-difference-with-examples