Steve Kuo
Steve Kuo

Reputation: 63054

How to reference a Grails domain class fields from outside of the Grails controller and view?

I have the domain classes:

class Child {
    static hasMany = [ toys : Toy ]
    String name
    Set  toys
}
class Toy {
    static belongsTo = [ owner : Child ]
    String name
}

In my JSP I reference a child by:

child = Child.findByName("Joe")

or

child = Child.findById(123)

But when I attempt to access its fields:

child.getToys()

I get the error:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: Child.toys, no session or session was closed

Do I need to manually start the Hibernate session? If so how would I do this?

Follow-up Feb 2012: This behavior is also present when running from the Grails console (Grails 2.0.0)

Upvotes: 3

Views: 3949

Answers (1)

Siegfried Puchbauer
Siegfried Puchbauer

Reputation: 6539

This relates to a flaw in Grails 1.0.4 regarding Hibernates Lazy Initialization. As a workaround you can force eager fetching of those properties:

child = Child.findByName("Joe", [ fetch: [ toys: 'eager' ] ] )

Apart from this, following the MVC principles, you should consider performing those queries inside the controller and making the results part of the model.

Btw. are you really doing this inside a JSP? Or is a GSP?

Cheers

Upvotes: 8

Related Questions