Java Hibernate-无法获取当前线程的事务同步会话
我理解这个问题已经被问了很多次,但大多数人都无法解释我的问题:Java Hibernate-无法获取当前线程的事务同步会话,java,hibernate,transactions,hibernate-session,Java,Hibernate,Transactions,Hibernate Session,我理解这个问题已经被问了很多次,但大多数人都无法解释我的问题: @RequestMapping("/testing") public String testing(HttpServletRequest request, final ModelMap model) { Transaction ut = session.openSession().beginTransaction(); session.getCurrentSession(); // error here
@RequestMapping("/testing")
public String testing(HttpServletRequest request, final ModelMap model)
{
Transaction ut = session.openSession().beginTransaction();
session.getCurrentSession(); // error here
ut.commit();
return "testing";
}
为什么我会出错
Could not obtain transaction-synchronized Session for current thread.
如果我用@Transactional
注释该方法,它工作得非常好。因为我在spring上下文中有@EnableTransactionManagement
我想尝试了解getCurrentSession
和openSession
之间的区别,所以我在上面创建了测试用例
getCurrentSession
在活动事务上下文中被调用,为什么它仍然抛出错误
参考中的代码。好的,经过这么长时间的研究,我发现我遗漏了以下内容: 您不会在常规应用程序中看到这些代码片段;致命的 (系统)异常应始终在“顶部”捕获。换句话说 换句话说,在持久化中执行Hibernate调用的代码 层,以及处理RuntimeException的代码(通常可以 仅清理和退出)位于不同的层中。当前环境 Hibernate的管理可以通过 访问SessionFactory。异常处理将在后面的中讨论 这一章 因此,这个例子显示,在常规情况下,确实不起作用 我必须做到以下几点:
// 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
}
这意味着,getCurrentSession
的使用受到很大限制,它必须在活动的
(和特定的)事务中运行