作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 Grails 中编写一个多线程应用程序,其他线程需要访问 GORM/Hibernate。当他们尝试访问 GORM 时,我收到错误“org.hibernate.HibernateException:没有绑定(bind)到线程的 Hibernate session ,并且配置不允许在此处创建非事务性 session ”。
好吧,公平地说,有人可以指导我设置线程以进行访问的最佳方式吗?错误消息听起来几乎就像您只需要更改一些配置选项但我感觉,它不是那么简单......
最佳答案
Luke Daley给出了正确的答案。不幸的是,链接已更改。因此,我将更新他的答案并提供一个代码示例以使该答案自成一体。
Grails 应用程序中有一个名为 persistenceInterceptor
的 bean。可用于为 Hibernate 初始化持久性上下文/ session 。您可以将 bean 注入(inject)您的 Controller /服务类之一并启动一个新线程,例如使用以下代码片段。
class YourControllerOrService {
PersistenceContextInterceptor persistenceInterceptor
def someOperation() {
...
Runnable yourTask = { ->
try {
if (persistenceInterceptor) {
persistenceInterceptor.init()
}
// execute the hibernate operations here in a transaction,
// e.g. call a method annotated with @Transactional
...
} catch (Exception e) {
log.error('Your error message', e)
} finally {
if (persistenceInterceptor) {
persistenceInterceptor.flush()
persistenceInterceptor.destroy()
}
}
}
Thread workerThread = new Thread(yourTask)
workerThread.start()
...
}
}
您将在
Grails JMS plug-in on GitHub 中找到示例性实现。 .
关于grails - 如何将 Hibernate Session 绑定(bind)到 Grails 中的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3556550/
我是一名优秀的程序员,十分优秀!