What is difference between get() and load() method of hibernate session with respect to fetching?
As T Mishra states here:
By default, hibernate creates run-time proxies. It loads the objects as a proxy unless a fetch mode is specified or set to false.
That's because once the object is loaded in cache, the next subsequent calls perform repeatable read.
- 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
Actually, both functions are use to retrieve an object with different mechanism,
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.
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.
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.