What is the difference between get() and load():
The most important question for the interview's perspectives that what is the difference between get and load methods in Hibernate? Developers use both the functions when coding but most of them use them without knowing the pros and cons of these methods.
In this article we will try to make you understand the similarities and difference between hibernate load and get methods.
Similarities between load() and get() methods :
- The load() and get() both methods
used to retrieve object (a row) from
database.
- Syntax wise both load() and get()
methods are same.
- load() method is older whereas
get() is new, but both belongs to
Hibernate API.
- load() and get() both methods
belongs to Session interface.
Difference between load() and get() methods : Suppose we have a Student student object having two fields id and name and it's getters and setters methods.
When we call the sesssion.load() method it will create the proxy or dummy object of Student class in the
memory, for example if we call session.load(101) then it will create a dummy object in the memory contains the id value 101 and value of name fields as null, but when we call the getName() method then it will hit the db and retrieve the row of the object id of 101. Whereas other method session.get() will direct hit the database to retrieve the value of the all fields of student object, for example session.get(101) will hit the database and fetch a record for identifier 101.
If session.load() can't find the object in the cache of database, it will throw the ObjectNotFoundException exception, but sesssion.get() not.
If session.get() can't find the object in the cache or database it will return null, but session.load() throws the ObjectNotFoundException exception.
Conclusion:
- The get() method hits the database and fetch the object as soon as we called the method but in load() method it fetched the record when needed, it supports the lazy loading. So load() is better then the get().
- We only needs to use load() when we are sure that data is present in the database otherwise it will throw the exception.
- We should use get() method when we want to check the data is present in db or not.
0 Comment(s)