org.hibernate.LazyInitializationException in a Quartz job

十年热恋 提交于 2019-12-07 17:13:58

问题


I can use dynamic finders on my domain classes in my Quartz job, but get org.hibernate.LazyInitializationException when accessing relationships. I thought they would either both work, or none.

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

Any idea why this might be happening? According to the Quartz plugin documentation each job thread gets a Hibernate session, yet I'm running into this problem.

Grails 2.1.1, quartz:1.0-RC9

Full Error:

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

回答1:


MyJob is not a grails artefact, hence not transactional by default. Associations which will be fetched lazily has to be under transactional boundary.

Solution:-
Follow @Alidad's comment.

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
    }
}



回答2:


By default GORM single-ended associations are lazy. See documentation for more info.



来源:https://stackoverflow.com/questions/17669340/org-hibernate-lazyinitializationexception-in-a-quartz-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!