Hello All,
I have a (newbie-ish) question about caching object references for entities that have lazily loaded members.
Should one ever cache object references to entities that contain lazily loaded entities as members, or instead should one only store entity id's and then use a session from Hibernate to load the object reference when needed (and only used with the context of that session)?
If you need more context, there is some more information below. Many thanks.
Suppose entity A contains entity B, and B is lazily loaded (is proxied). A (naive) architecture might involve an A factory that provides A's, with an A lookup method implementation like this:
Code:
A LookupA(int id)
{
if (!(cached(id))
{
Session s = mSessions.openSession();
Transaction t = s.BeginTransaction();
A a = (A)s.Load(A.class, id);
addToCache(a);
t.commit();
s.close();
}
return getFromCache(id);
}
Notice that the factory is caching the object references to A's.
Should one ever have factories (or any object) do this? Or instead should we always rely on Hibernate to fetch object references for us (ie. Always create a new session and do the .Load()), and depend on its caching scheme?
I'm asking, because I know that lazily evaluated proxies are tied to a session, and if you close the session (or commit a transaction) before a proxied abject has loaded its state, you get an error. Therefore, if a reference to A is cached anywhere, and the session from which it has been closed, then trying to load B results in an error.
I'm wondering if the intention is to always use Hibernate to cache object references, and no one else should ever do that? If so, what if there is some transient object that wants a reference to an entity - should it then store the id for the entity and use Hibernate (with a session) to get the reference when it needs it?
Many many thanks to all.
Code: