如何从Grails控制器和视图之外引用Grails域类字段? [英] How to reference a Grails domain class fields from outside of the Grails controller and view?

查看:109
本文介绍了如何从Grails控制器和视图之外引用Grails域类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有域类:

  class Child {
static hasMany = [toys:Toy]
字符串名称
设置玩具
}
class玩具{
static belongsTo = [owner:Child]
字符串名称
}

在我的JSP中,我通过引用一个孩子:

  child = Child.findByName(Joe)

  child = Child.findById(123)

但是,当我尝试访问其字段时:

  child.getToys()

我得到这个错误:

  org.hibernate.LazyInitializationException:未能懒惰地初始化一个角色集合:Child.toys,没有会话或会话已关闭

我是否需要手动启动Hibernate会话?如果是的话,我该怎么做?



2012年2月后续:从Grails控制台运行时也存在此行为(Grails 2.0 .0)解决方案

这与Grails 1.0.4中关于Hibernates延迟初始化的一个缺陷有关。作为解决方法,您可以强制提取这些属性:

  child = Child.findByName(Joe,[fetch:[玩具:'eager']])

除此之外,遵循MVC原则,您应该考虑执行这些查询在控制器中,并使结果成为模型的一部分。

顺便说一句。你真的在JSP内部做这个吗?或者是普惠制?



干杯


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)

解决方案

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

这篇关于如何从Grails控制器和视图之外引用Grails域类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆