2

我知道这个问题已经被问过很多次了,但大多数都无法解释我的问题:

@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,它工作得非常好。因为我@EnableTransactionManagement在我的春天背景下。

我想尝试一些东西来理解和之间的区别getCurrentSessionopenSession所以我在上面创建了测试用例。

getCurrentSession在活动事务上下文中被调用,为什么它仍然抛出错误???

参考这里的代码

4

1 回答 1

0

好的,经过这么长时间的研究,我发现我错过了以下段落

您不会在常规应用程序中看到这些代码片段;致命(系统)异常应始终在“顶部”捕获。换句话说,在持久层执行 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非常有限,它必须在一个active(和特定的)事务中运行。

于 2016-10-03T01:32:36.323 回答