Quartz作业中的org.hibernate.LazyInitializationException

时间:2013-07-16 06:17:28

标签: grails gorm quartz-scheduler

我可以在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.1quartz: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

2 个答案:

答案 0 :(得分:7)

MyJob不是grails artefact,因此默认情况下不是事务性的。将懒惰地取出的协会必须处于交易边界之下。

<强>解决方案: -
关注@ 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
    }
}

答案 1 :(得分:0)

默认情况下,GORM单端关联是懒惰的。有关详细信息,请参阅documentation