views:

1665

answers:

1

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?

+5  A: 

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

Siegfried Puchbauer
It's from a JSP. I'm retrofitting a legacy application which queries from the view. I should just change it to follow Spring/Grails's MVC pattern.
Steve Kuo
I tried setting fetch to eager but now toys is missing most of its content. In other words, if I don't specify fetch eager, all the toys are loaded. If I specify fetch eager, then only 10-20% of toys are loaded.
Steve Kuo
That's weird. I've seen the issue in the JIRA (GRAILS-3712). As a final workaround you could define the collections you use in the views to be eagerly fetched by default:// (within the domain class)static mapping { toys lazy: false}That should solve the problem for now.
Siegfried Puchbauer