I am trying to understand what the difference is in returned object and behavior of Hibernate 3.6 session.get()
and session.load()
.
From the javadoc:
get():
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.)
load():
Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.
I have three questions:
The javadoc does not say when
load()
might return a proxy - is there any way to know it in advance?When
load()
returns a proxy - this meansload()
did not access the database, am I correct? Then what if I providedload()
with an identifier that does not exist in the database? I will now have in the session a proxy with an invalid ID (without getting an Exception). Now I want to let another persistent instance point to that proxy - is it going to work? For this scenario I do not need to initialize the proxy, I only need its id (which I have even though its invalid since it's not in the database). So I guess I am asking if my description is correct, and do I always need to check out afterload()
the returned object withisInitialized()
in order to make sure it represents a valid entity (or at least a valid proxy), i.e. with a valid ID.Also, what happens if
load()
returns a proxy - so the proxy is the instance that is already associated with the session. Then according to the description ofget()
: "If the instance is already associated with the session, return that instance." - so doesget()
return the proxy? Since according to the description ofget()
: "This method never returns an uninitialized instance."
Thanks!
UPDATE
Are the following correct?
(A) I think both load()
and get()
will first try to check the session cache before going to the DB - so it would not be right to say that any of them always hits the DB, or always returns a proxy.
(B) An initialized proxy is not the same as the original instance, as you can read here: http://blog.xebia.com/2008/03/08/advanced-hibernate-proxy-pitfalls/