18 December 2008

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( user.id ) // 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.

0 comments: