wolfgang2006 wrote:
So my questions are :
1. What's difference between Session#load(...) and Session#get(...) other than throwing an exception or not ?
2. Why does accessing a persistent object retrieved by load(...) throw an exception after closing session while one retrieved by get(...) doesn't ?
(If possible, could someone briefly explain me the underlining implementation of those two methods ?)
You should have a look here :
http://www.hibernate.org/hib_docs/v3/re ... te-loading
You'll understand all you're asking for.
Briefly, you get the main facts :
* load() returns a lazyloaded dynamic-proxy.
* get() returns a "real" instance, though directly accessing the data in database.
That said, the answer to your second question is quite obvious : accessing the reference that has been loaded by load() triggers the database query, right ? So you see why you're receiving a LazyInitializationException with load, if you close the session before accessing the data.
With load, you HAVE to access a property of the object to be able to access it after closing the session. If not, you'll get LazyInitException. But if you do it, the proxy will have been loaded and you won't get this exception anymore, even if you access it once more after closing the session.
Example 1 :
Code:
Session session = HibernateUtil.currentSession();
session.beginTransaction();
logger.debug("before load()");
Client c = (Client) session.load(Client.class, "1");
logger.debug("after load()");
session.getTransaction().commit();
session.close();
logger.debug(c);
This code throws the LazyInitException.
Example 2 :
Code:
Session session = HibernateUtil.currentSession();
session.beginTransaction();
logger.debug("before load()");
Client c = (Client) session.load(Client.class, "1");
logger.debug("after load()");
//access the client before closing the session
logger.debug(c);
session.getTransaction().commit();
session.close();
logger.debug(c);
This code
does NOT throw the LazyInitException.
To sum up, depending on what you want to do, you decide if you want to load() or get() your data, for example, you could use load() if you don't want data to be always loaded. Personnally, most of the time, I use get, because of the inherent risk caused by the lazy-loading. So I always load completely my data when I need it.
OK ?