【问题标题】:Hibernate - Could not obtain transaction-synchronized Session for current threadHibernate - 无法获取当前线程的事务同步会话
【发布时间】:2017-01-01 07:40:57
【问题描述】:

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

@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 在一个活动的事务上下文中被调用,为什么它仍然抛出错误???

参考this的代码。

【问题讨论】:

    标签: java hibernate transactions hibernate-session


    【解决方案1】:

    好的,经过这么长时间的研究,我发现我错过了下面的paragraph

    您不会在常规应用程序中看到这些代码 sn-ps;致命的 (系统)异常应始终在“顶部”捕获。其他 换句话说,在持久化中执行 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(和特定的)事务中运行。

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 2015-04-11
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多