What is the difference between Hibernate Get() function and Load function ? Which one is preferred when ?
-
possible duplicate of [Hibernate: Difference between session.get and session.load](http://stackoverflow.com/questions/608947/hibernate-difference-between-session-get-and-session-load) – Jon Skeet Dec 27 '13 at 11:14
3 Answers
load()
will return a proxy of the row or object in the database. It will throw an ObjectNotFoundException
. It will never return null
.
get()
represents an actual row in the database, so it is not a proxy and will not throw an exception if not found, but will return null
.

- 10,998
- 11
- 48
- 78
Difference between get and load method Here are few differences between get and load method in Hibernate.
Behavior when Object is not found in Session Cache Apart from performance this is another difference between get and load which is worth remembering. 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.
Database hit Get method always hit database while load() method may not always hit the database, depending upon which method is called.
Proxy Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using returned object for creating relationship and only need Id then load() is the way to go.
Performance By far most important difference between get and load in my opinion. get method will return a completely initialized object if Object is not on the cache but exists on Database, which may involve multiple round-trips to database based upon object relational mappings while load() method of Hibernate can return a proxy which can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason use of load method will result in slightly better performance, but there is a caveat that proxy object will throw ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately so not a fail fast behavior.
load method exists prior to get method which is added on user request.

- 1
- 1

- 10,826
- 1
- 21
- 40
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 Object Not Found Exception.
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.

- 51
- 5