What is difference between get() and load() method of hibernate session with respect to fetching?

StackOverflow https://stackoverflow.com/questions/22142920

  •  19-10-2022
  •  | 
  •  

Question

What is difference between get () and load() method? with respect to data fetching approach

 public static void main(String[] args) {
    SessionFactory factory= new Configuration().configure().buildSessionFactory();
     Session session = factory.openSession();
     Transaction tx = null;
      tx = session.beginTransaction();
       System.out.println("1 st time calling load method");
        Account acc = 
               (Account)session.load(Account.class, 180); 
             System.out.println("bal"+acc.getBalance());

          System.out.println("2nd   time calling load method");
          Account  acc1=(Account)session.load(Account.class, 180); 
           System.out.println("bal"+acc1.getBalance());


        System.out.println("1 st time calling get method");
     Account acc2= (Account) session.get(Account.class, accId);

      System.out.println("bal"+acc2.getBalance());    

      System.out.println("2 st time calling get method");

     Account  acc2= (Account) session.get(Account.class, accId);

    System.out.println("bal"+acc2.getBalance());


     tx.commit();

   session.close(); 

}

I got following output

1 st time calling load method
Hibernate: 
/* load com.abcd.Account */ select
    account0_.ACCOUNTID as ACCOUNTID1_0_,
    account0_.ACCOUNTTYPE as ACCOUNTT2_1_0_,
    account0_.CREATIONDATE as CREATION3_1_0_,
    account0_.BALANCE as BALANCE1_0_ 
from
    a.MYACCOUNT account0_ 
where
    account0_.ACCOUNTID=?
bal3000.0
2nd   time calling load method
bal3000.0
1 st time calling get method
bal3000.0
2 st time calling get method
bal3000.0

From ouput it is clear that get method did not hit database.It behaves like load() method. Could any one tell me is this behavior correct.

Was it helpful?

Solution

As T Mishra states here:

  1. By default, hibernate creates run-time proxies. It loads the objects as a proxy unless a fetch mode is specified or set to false.

  2. That's because once the object is loaded in cache, the next subsequent calls perform repeatable read.

  3. Although the state of this object changes from persistent to detached

The entity can be retrieved in 2 ways.

load() - returns the proxy object with an identifier.

get() - returns the complete object from database.

for more details click this link

OTHER TIPS

Actually, both functions are use to retrieve an object with different mechanism,

  1. session.load()

    It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object. If no row found , it will throws an ObjectNotFoundException.

  2. session.get()

    It always hit the database and return the real object, an object that represent the database row, not proxy. If no row found , it return null.

When you call session.load() method, it will always return a “proxy” object, whats the meaning of proxy object ? Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting the database, for example if we call session.load(Student.class,new Integer(107)); > hibernate will create one fake Student object [row] in the memory with id 107, but remaining properties of Student class will not even be initialized. enter image description here

GET

When you call session.get() method, it will hit the database immediately and returns the original object. If the row is not available in the database, it returns null.

hibernatesession.get() will fetch the real object from the database and hibernatesession.load() will return proxy without hitting the database. For more details click here. It explains get and load method and their difference with example codes.

Use load:

  • If you are sure about the object availability that you are retrieving from DB. Else you will end up catching ObjectNotFoundException.

  • When you have heavy object to be loaded (Since it loads lazily whenever you use it)

Use get:

  • If you are not sure about the object availability in the DB.
  • You get luxury to check for null, when there is not object available in DB.
  • When you have light object to be loaded (since it loads eagerly).

** Load:** Whenever the load() method is called, the hibernate creates a proxy object of a POJO class, and it will set the id to the proxy object, then it returns the proxy object to the program. Based on the operations performed on the proxy object, the hibernate will decide whether to go cache or database to load the data. This process is called lazy loading.

** Get:** When we call the get() method, then hibernate first goes to first level cache and if that object doesn’t exist in the first level cache then it goes to the database and loads the object from the database. If Id doesn’t exist in the database, then get() method returns null. When get() method is called no proxy object is created, hence it is called as early loading.

Ref : http://docs.jboss.org/hibernate/orm/4.3/javadocs/

Complete Example you can find @ my blog: http://www.onlinetutorialspoint.com/hibernate/hibernate-session-differences-between-load-and-get.html

Here is a simple explanation of what you need: http://www.mkyong.com/hibernate/different-between-session-get-and-session-load/

Or by looking at the API: http://docs.jboss.org/hibernate/orm/4.3/javadocs/

with get : Return the persistent instance of the given named entity. The persistent one, so the one stored in the database.

with load: Read the persistent state associated with the given identifier into the given transient instance.

In the first link you find very useful examples to test the differences..

Load: when we call session.load() method it doesn't hit directly database. It creates and return proxy object if object didn't belongs in db it throws "ObjectNotFountException". And supports lazy loading.

Get: It hits directly object in db and gives original value if object not found then it returns null. And it supports eager loading.

From the above example - both the functions are not working same.

load() - hibernate will only load proxy of the object with the specified ID. All the properties will not be set in advanced. Once you call the getter methods on the object, the query will be issues. So when you can a getAccount method , select query will be issued and the result object will be saved in cache as it is retrieved by ID. So any subsequent calls via get will not result any select statement.

get() - will always retrieve the object from database with full properties populated. For properties defined in collections, depends on lazy initialization configuration. Please note - Any subsequent calls on the same session will return the object from the cache only and hence no queries will be returned. That is what happening with the call to get method in the first time and the second time as the object is ready in cache by calling the acc.getBalance() on the object retrieved by load.

Don't forget performance aspect between get and load method

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.

You can see the example that demo this difference on the tutorial Difference between get and load method in Hibernate

When you call session.load() method, it will always return a proxy object, whats the meaning of proxy object ? Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting the database, for example if we call.

 session.load(Student.class,new Integer(107)); 

hibernate will create one fake Student object [row] in the memory with id 107, but remaining properties of Student class will not even be initialized, observe this graphical representation…

It will hit the database only when we try to retrieve the other properties of Student object I mean stdName, stdCountry.
If we call s2.getStdName() then hibernate will hit the database and search the row with student id 107 and retrieve the values, if object [row] not found in the database it will throws ObjectNotFoundException.


 session.get()

When you call session.get() method, it will hit the database immediately and returns the original object. If the row is not available in the database, it returns null.


So which is the best method to use, hibernate load() or get()? It's completely your choice .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top