Tropical Software Observations

18 December 2008

Posted by Unknown

at 10:56 AM



Grails 1.0.4 "no Session" Error

In Grails 1.0.4, there are a few significant changes to how GORM returns Model objects from queries or model traversal.

If you're getting "Could not initialize proxy - no Session" exceptions when trying to access a domain object's collection of child objects, check that you aren't storing the domain object in a HTTP session, as when model objects are stored in the session, they're detached. Prior to version 1.0.3, the detached object had enough information as it was "eagerly fetched". With 1.0.4, this is no longer the case as it's just a proxied object.

To prevent this problem, before you access the object's child collection do the following:

def user = session.user
user.refresh() // Either refresh the object to attach it back to the session
user = User.get( ) // Or retrieve back the object with its id
user.profiles[0] // Then doing stuff like this won't throw the error anymore

For more discussion and context, read this message thread.


David Gelbart said...

Thanks, this is potentially very helpful. I couldn't find this page when Googling the full exception so to help others, here it is: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

David Gelbart said...

The message thread link above is broken now. Try here:

David Gelbart said...

There's a section about this problem in the book Grails Persistence with GORM and GSQL ($14 ebook, $20 book). The section is titled Lazy Initialization and the Grails Session. The recommended solution is this:

def hibSession = sessionFactory.currentSession

user = hibSession.merge(user)

I suppose that using the user.refresh or User.get approach from this blog post results in re-reading the object from the DB and thus losing any changes that have been made to the object.