开发者

failed to lazily initialize a collection of role

开发者 https://www.devze.com 2023-02-07 13:21 出处:网络
Hey all, I\'m building a GRAILS application with a m:m db relation. As I try to show the entries the well known \"failed to lazily initialize a collection of role ... no session or session was closed\

Hey all, I'm building a GRAILS application with a m:m db relation. As I try to show the entries the well known "failed to lazily initialize a collection of role ... no session or session was closed" error is shown.

One class is:

class Hazzard{

static hasMany = [warning:Warning]

static constraints = {
    text(size:1..5000)
}

    String name
    String text
    String toxicity
}

the other:

class Warning{

static hasMany = [hazzard:Hazzard]
static belongsTo = Hazzard

static constraints = {
    text(size:1..5000)
}

    String code
    String text   
}

In Hazzard/show the following code works fine

<g:each in="${hazzardInstance.warning}" var="p">
<l开发者_运维技巧i><g:link controller="Warning" action="show" id="${p.id}">${p?.encodeAsHTML()}</g:link></li>
</g:each>

but on other pages the following code will provide the error:

<g:set var="haz" value="${Hazzard.get(params.id)}" />
<h1>${haz.name}</h1>
<p>${haz.text}</p>
<h1>Toxiciteit</h1>
<p>${haz.toxicity}</p>
<br/>
<h1>Gevaren(H) en voorzorgen(P)</h1>
<g:each in="${haz.warning}" var="p"> --> This is where the error pops-up
  ${p.text}
</g:each>

Any clues on where this fails?


A more favorable approach to what you're trying to do would be to perform the get in the controller and pass the found domain object to the view for rendering. Something like:

// MyController.groovy
class MyController {
    def myAction = {
        def haz = Hazzard.get(params.id)
        render(view: 'myview', model: [hazzardInstance: haz])
    }
}

// my/myview.gsp (the view from your second GSP code block)
<h1>${hazzardInstance?.name.encodeAsHTML()}</h1>
...
<h1>Gevaren(H) en voorzorgen(P)</h1>
<g:each in="${hazzardInstance?.warning}" var="p">...</g:each>

Doing GORM lookups in the view can sometimes lead to the exception you're getting, although I thought many problems like that had been fixed in more recent versions of Grails. Nonetheless, using a more correct idiom for querying and rendering views will help you to avoid this error.

0

精彩评论

暂无评论...
验证码 换一张
取 消