Both get() and load() methods reside inside Hibernate's Session interface. Both do the same thing, to retrieve an object from the database. This object is nothing but a row from the table based on some query passed. The difference lies in the process of retrieval. Let's discuss each method in detail.
session.get() method is pretty straight-forward. We select a row from the table using an ID, and retrieve the data.
Lets say we have a table with roll number and name. Roll number is primary key, so we try to access the row based on its value.
When we call session.load() method, it doesn't search the table and returns the row directly, instead it returns a proxy object. Proxy object signifies that the object returned is not the real object containing table data. It is created in heap memory with an ID as passed.
When we try to access some value other than ID, then only the object searches the database and returns the data object(if present).
Here's a code snippet to clarify any doubts:
The difference between Hibernate get() and load() methods is in the return value when the identifier does not exist in database:
|get() method||load() method|
|We will get nullPointerException if identifier is not present.||We will get objectNotFoundException Exception if identifier is absent.|
|get() method provides data implementation of eager loading i.e It loads all data initially||load() method provides data implementation of lazy loading i.e It loads data when it is actually needed.|
|get() method can be used in both attached(session is open) as well as detached(session is closed) state.||load() method can be used only in attached mode, if we try to use load method in detached state LazyInitializationException is thrown.|