[英]Hibernate - Could not obtain transaction-synchronized Session for current thread
I understand this question has been asked many time, but most can't explain my problem: 我知道这个问题已经问了很多次了,但是大多数人无法解释我的问题:
@RequestMapping("/testing")
public String testing(HttpServletRequest request, final ModelMap model)
{
Transaction ut = session.openSession().beginTransaction();
session.getCurrentSession(); // error here
ut.commit();
return "testing";
}
Why I am getting the error 为什么我得到错误
Could not obtain transaction-synchronized Session for current thread.
If I annotate the method with @Transactional
, it is working perfectly fine. 如果我用
@Transactional
注释该方法,则它工作得很好。 Because I have @EnableTransactionManagement
in my spring context. 因为我的春季上下文中有
@EnableTransactionManagement
。
I want to try something to understand the difference between getCurrentSession
and openSession
, so I created test case above. 我想尝试一些东西来理解
getCurrentSession
和openSession
之间的区别,所以我在上面创建了测试用例。
getCurrentSession
is called within a active Transaction context, why it is still throwing me error??? 在活动的事务上下文中调用
getCurrentSession
,为什么它仍然引发我错误?
OK, after so long time of research, I found out I have miss out the paragraph below: 好吧,经过这么长时间的研究,我发现我错过了以下段落 :
You will not see these code snippets in a regular application;
您不会在常规应用程序中看到这些代码片段。 fatal (system) exceptions should always be caught at the "top".
致命(系统)异常应始终捕获在“顶部”。 In other words, the code that executes Hibernate calls in the persistence layer, and the code that handles RuntimeException (and usually can only clean up and exit), are in different layers.
换句话说,在持久层执行Hibernate调用的代码和处理RuntimeException的代码(通常只能清理和退出)位于不同的层。 The current context management by Hibernate can significantly simplify this design by accessing a SessionFactory.
Hibernate当前的上下文管理可以通过访问SessionFactory大大简化此设计。 Exception handling is discussed later in this chapter.
异常处理将在本章后面讨论。
So the example showing there indeed will not be working in regular scenario... 因此,显示该示例的示例确实无法在常规情况下使用...
I have to do as below: 我必须做如下:
// BMT idiom with getCurrentSession()
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work on Session bound to transaction
factory.getCurrentSession().load(...);
factory.getCurrentSession().persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
Which mean, the usage of getCurrentSession
is pretty restricted, it must be running in a active
(and specific) transaction. 这意味着,
getCurrentSession
的使用受到严格限制,它必须在active
(特定)事务中运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.