3

我可以在我的工作中对我的域类使用动态查找器Quartz,但org.hibernate.LazyInitializationException在访问关系时获取。我以为他们要么都工作,要么都不工作。

class MyJob {
    def author = Author.list().first() // fine
    def book = Book.get(1) // fine
    println author.books // lazy exception
}

知道为什么会发生这种情况吗?根据 Quartz 插件文档,每个作业线程都有一个 Hibernate 会话,但我遇到了这个问题。

Grails 2.1.1,quartz:1.0-RC9

完全错误:

2013-07-16 16:08:10,008 [quartzScheduler_Worker-10] ERROR grails.plugins.quartz.listeners.ExceptionPrinterJobListener  - Exception occurred in job: null
org.quartz.JobExecutionException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: test.Author.books, no session or session was closed [See nested exception: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: test.Author.books, no session or session was closed]
    at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:96)
    at grails.plugins.quartz.QuartzDisplayJob.execute(QuartzDisplayJob.groovy:29)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: test.Author.books, no session or session was closed
    at test.MyJob$_execute_closure1$$EOBjSWum.doCall(MyJob.groovy:7)
    at test.MyJob$$EOBjSWum.execute(MyJob.groovy:7)
    at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:89)
    ... 3 more
4

2 回答 2

7

MyJob不是 grails 人工制品,因此默认情况下不是事务性的。将延迟获取的关联必须在事务边界下。

解决方案:-
关注@Alidad 的评论。

class MyJob {
    def author = Author.list().first()
    def book = Book.get(1)
    Book.withTransaction{
        //withSession can also be used. You can also use Autor.withTransaction. 
        //The entity reference is immaterial.
        println author.books
    }
}
于 2013-07-16T13:41:31.273 回答
0

默认情况下,GORM 单端关联是惰性的。有关更多信息,请参阅文档

于 2013-07-16T13:19:45.600 回答