Hibernate Session provides two methods to access the object
(session.get() & session.load()). Both looks like same but there are
differences between load () and get () methods. Let’s have a look at those.
load():
§ load() method
throws hibernate.ObjectNotFoundException (which is
Un-checked exception) if object not found in cache as well as in database.
§ load() method
is lazy loading i.e. when you call
session.load(Class,identifier) method, it will return Proxy object but not entity
§ Use load() method
when you are sure that the object exists in database.
§ load() method is
equivalent to getReference() method of JPA.
§ Since load() method
returns proxy object, so it is not fully available in any future detached
state. Detached state means Object is not associated with Session, but present
in Database. So if you are not working with detached objects load() or getReference() methods can be used to
have better performance.
get():
§ get() method
returns NULL , if object is not found in cache as well as
in database.
§ get() method is early loading e. when you
call session.get(Class,identifier) method, it will hit the database immediately
,loads the entity object and returns the entity object.
§ Use get() method if
you are not sure that the object exists in database.
§ It is equivalent to
EntityManager.find() method of JPA.
§ Since get() returns a
fully initialized object, so it is fully available in any future detached
state.
When
to use get() and load():
1) Requirement:
If object is present you need to implement some logic otherwise you need to
implement some other logic.
get(): if object is not returned with get method,
it returns null, so we can implement above requirement as below.
If(object ==null) {
//some logic
} else {
//some other
logic
}
load(): If
object is not returned it throws Exception, so we cannot use load() method for
this requirement.
So,
we need to use get() method for the above requirement.
2)
Use load() method if your code doesn’t access any method other
than the identifier. It just returns the proxy object.
No comments:
Post a Comment