Tuesday, February 2, 2010

Advantage of Hibernate session load() vs get()

If load() can’t find the object in the cache or database, an exception is
thrown.
The load() method never returns null.

The get() method returns
null if the object can’t be found.

The get() method will return a FULL initialized object if nothing is on the session cache, that means several DB hits depending on your mappings.

While the load() method will return a proxy (or the instance if already initialized), allowing lazy initialization and thus better performance

Choosing between get() and load() is easy: If you’re certain the persistent
object exists, and nonexistence would be considered exceptional, load() is a
good option. If you aren’t certain there is a persistent instance with the given
identifier, use get() and test the return value to see if it’s null.

No comments: