Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 386
Steve Kuo Avatar asked Nov 28 '25 22:11

Steve Kuo


1 Answers

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

like image 84
Siegfried Puchbauer Avatar answered Nov 30 '25 16:11

Siegfried Puchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!