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 .