zoran119
zoran119

Reputation: 11307

org.hibernate.LazyInitializationException in a Quartz job

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

Upvotes: 3

Views: 3368

Answers (2)

dmahapatro
dmahapatro

Reputation: 50245

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

Upvotes: 7

Aram Arabyan
Aram Arabyan

Reputation: 2359

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

Upvotes: 0

Related Questions