Grails:: I hate and simply can't unerstand: 'No hibernate session bound to current thread'
A simple scenario but making me bang my head against wall, as I'm unable to understand this 'No Hibernate Session bound to current thread'.
Use case to implement:
def records = SomeDomain.list()
//split records into equal size chunks.
def chunks = [][] // <- add records to chunks
//now process each chunk in a different thread
chunks.each { aChunk ->
Thread.start {
singletonInjectedService # processs(aChunk)
}
}
How to achieve this in grails? No matter what is the container, a Quartz Job which wants to process the 'records' in multiple threads or a Service which wants to process 'records' in multiple threads, it simply fails with 'No hibernate session bound t开发者_JAVA百科o current thread'.
A legitimate use case but pity that its just not working for me at all.
This is what happens when you try to do something asynchronously managing your own threads. In a web application, when a request comes in, it is handled in a thread by the container. The container/spring will typically bind some resources to the thread of execution, resources like the current hibernate session. When you fire off your own threads, the existing resources on the current thread don't magically appear on your new threads.
When you manage your own threads, weird things are going to happen.
That said, there is a withTransaction method available on domain classes, documented here: http://grails.org/doc/latest/ref/Domain%20Classes/withTransaction.html which should take care of your problem.
Also there is a background thread plugin, seen here http://grails.org/BackgroundThread+Plugin that claims to take care of the hibernate session issue for you.
精彩评论