Thursday, March 19, 2009

LazyInitializationException has a misleading error message

You'll get a LazyInitializationException if you try to load an object from Hibernate, clear the Hibernate session, then lazily initialize a collection on the object like so:

Customer customer = loadCustomerUsingHibernate();
hibernateSession.clear();
customer.getAddresses(); // LazyInitializationException!!

In this situation, the session still exists and has not been closed. Yet the default error message on LazyInitializationException proclaims: "No session or session is closed"

This error message is misleading and led me up the garden path. The cause of the exception here is that the first level hibernate cache has been cleared, and customer is now a detached object. It has nothing at all to do with a closed or missing session!

I guess if you view it from the perspective of the detached customer object, there is no session to be found, so the message sort of makes sense - but I usually view things from my perspective (the developer), and when it says there is no session it is confusing for me.

0 comments: