From the API, I could see it has something to do with proxy. But I couldn't find a lot of information on proxy and do not understand the difference between calling session.get
and session.load
. Could someone please explain or direct me to a reference page?
Thank you!!
One more Extra point::
get method of Hibernate Session class returns null if object is not found in cache as well as on database. while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.
load() can’t find the object from cache or database, an exception is thrown and the load() method never returns null.
get() method returns null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance get() never returns a proxy.
An excellent explanation is found at http://www.mkyong.com/hibernate/different-between-session-get-and-session-load
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.
It will always return a proxy object with the given identity value, even the identity value is not exists in database. However, when you try to initialize a proxy by retrieve it’s properties from database, it will hit the database with select statement. If no row is found, a ObjectNotFoundException will throw.
session.get() :
It always hit the database(if not found in cache) and return the real object, an object that represent the database row, not proxy.
If no row found , it return null.
session.load() 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() 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.
Performance with these methods also makes diff . between two...
Also we have to be careful while using load as it will throw an exception if the object is not present. We have to use it only when we are sure that object exists.
Well, in nhibernate at least, session.Get(id) will load the object from the database, while session.Load(id) only creates a proxy object to it without leaving your server. Works just like every other lazy-loaded property in your POCOs (or POJOs :). You can then use this proxy as a reference to the object itself to create relationships, etc.
Think of it like having an object that only keeps the Id and that will load the rest if you ever need it. If you're just passing it around to create relationships (like FKs), the id is all you'll ever need.