Saturday, August 30, 2014

Difference between Get and Load method in Hibernate Get VS Load methods in Hibernate

Difference between Get and Load method in Hibernate  Get VS Load methods in Hibernate ? 

The difference between and get and load method is one of the most frequent asked question in hibernate. This question answer lets lot of about hibernate concepts. Hibernate session(session class is not thread safe) class get and load method, both of these methods used to access data, main difference between get() and load() method is that get() hits database if object doesn't exists in Session Cache and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object.


Difference between get and load method

1. Database : 
Get method always hit database while load() method may not always hit the database, depending upon which method is called.

2. Behavior of get vs load when Object not found in session cache : 
Get method of Hibernate Session class returns null if object is not found in session 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.

3. 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

4. Performance : 
In interview most of the time ask which method have better performance 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 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 ObjectNotFoundExceptionRead

No comments:

Post a Comment