In Hibernate, when to use get() method and load() method?

Answered

In Hibernate, when to use get() method and load() method?

Ninja Asked on 17th September 2018 in Hibernate.
Add Comment
1 Answer(s)
Best answer

The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder that triggers the loading of the real object when it’s accessed for the first time; On the other hand, get() never returns a proxy.

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. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.

Ninja Answered on 17th September 2018.
Add Comment