Grails:: 我讨厌并且根本无法理解:“没有休眠会话绑定到当前线程”
这是一个简单的场景,但让我头撞墙,因为我无法理解这个“没有 Hibernate 会话绑定到当前线程”。
实施用例:
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)
}
}
如何在 grails 中实现这一点?无论容器是什么,想要在多个线程中处理“记录”的 Quartz Job 或想要在多个线程中处理“记录”的服务,它都会失败,并显示“没有休眠会话绑定到当前线程”。
一个合法的用例,但遗憾的是它根本不适合我。
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 to current thread'.
A legitimate use case but pity that its just not working for me at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您尝试异步管理自己的线程时,就会发生这种情况。在 Web 应用程序中,当请求传入时,容器会在线程中处理该请求。容器/spring 通常会将一些资源绑定到执行线程,例如当前的 hibernate 会话等资源。当您关闭自己的线程时,当前线程上的现有资源不会神奇地出现在您的新线程上。
当你管理自己的线程时,奇怪的事情就会发生。
也就是说,域类上有一个可用的 withTransaction 方法,记录如下: http ://grails.org/doc/latest/ref/Domain%20Classes/withTransaction.html
这应该可以解决你的问题。
还有一个后台线程插件,可以在这里看到 http://grails.org/BackgroundThread+Plugin 声称为您解决休眠会话问题。
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.