Search code examples
hibernategrailsgrails-orm

Can I commit inside withTransaction closure


Can I commit inside the withTransaction closure? I want to do something like this inside my Quartz job:

Author.withTransaction {
    def author = Author.get(1)
    author.staus = 'processing'
    author.save()
    commit // how can i do this?
    // so some work here which takes 1-2 minutes
    author.status = 'completed'
    author.save()
}

The idea is that I want to have a status screen which will show all the Authors which are being processed at the moment, so I want to set the status to processing and be able to see this status from a controller.

EDIT: This would work without withTransaction, but I have to have withTransaction there... see this question.


Solution

  • In order to read values from a different uncommitted transaction, your database isolation level has to be set to "read uncommitted" which is often an indicator you might be doing something wrong.

    Is there any reason you couldn't separate this into separate transactions? One to mark the records as "in-progress" and one to perform the actual work?

    Author.withTransaction {
        def author = Author.get(id)
        author.status = 'processing'
        author.save()
    }
    
    Author.withTransaction() {
        def author = Author.get(id)
        // do some work
        author.status = 'completed'
        author.save()
    }