由save is not vaild without active transcation引发的问题

来源:互联网 发布:网络交友平台有哪些 编辑:程序博客网 时间:2024/05/18 17:56

引发问题的原因:

在ssh框架下,sessionFactory配置文件中
应用spring管理事务,并将应将hibernate.current_session_context_class设为thread 则会报该异常。

解决方案:

最简单的方案就是删除:hibernate.current_session_context_class设置删除.


知识点:

在一个应用程序中,DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。
- 在3.0版本之前,使用Hibernate的程序要么采用自行编写的基于 ThreadLocal的上下文session,要么采用HibernateUtil这样的辅助类,要么采用第三方框架(比如Spring), 它们提供了基于代理(proxy)或者基于拦截器(interception)的上下文相关session。
- 从3.0.1版本开 始,Hibernate增加了SessionFactory.getCurrentSession()方法.sessionFactory.getCurrentSession()可以完成一系列的工作,当调用时hibernate将session绑定到当前线程,事务结束后hibernate将session从当前线程中释放并且关闭session。当再次调用getCurrentSession()时将得到一个新的session,并重新开始这一系列工作。


在 SessionFactory 启动的时候, Hibernate 会根据配置创建相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,实际被执行的方法是CurrentSessionContext.currentSession() 。在 currentSession() 执行时,如果当前 Session 为空,currentSession 会调用SessionFactory的openSession 。所以getCurrentSession() 对于 Java EE 来说是更好的获取 Session 的方法。
* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()创建的session则不会
* 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()创建的session必须手动关闭

阅读全文
0 0