码迷,mamicode.com
首页 > 编程语言 > 详细

atitit.spring hibernate的事务机制 spring不能保存对象的解决

时间:2017-05-24 10:05:51      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:3.0   保存   upd   rgb   事务管理   lov   .net   配置   好的   

atitit.spring hibernate的事务机制 spring不能保存对象的解决

 

sessionFactory.openSession()

不能。

log黑头马sql语言..

 

 

 

sessionFactory.getCurrentSession().update(user);

中间走ok..log黑头也有累..

 

 

Spring中使用Hibernate。假设我们配置了TransactionManager。那么我们就不应该调用SessionFactoryopenSession()来获得Sessioin。由于这样获得的Session并没有被事务管理。

 

作者:: 老哇的爪子 Attilax 艾龙,  EMAIL:1466519819@qq.com

转载请注明来源: http://blog.csdn.net/attilax

 

 

採用getCurrentSession()创建的session会绑定到当前线程中,而採用openSession()创建的session则不会。

採用getCurrentSession()创建的sessioncommitrollback时会自己主动关闭。而採用openSession()创建的session必须手动关闭。

使用getCurrentSession()须要在hibernate.cfg.xml文件里增加例如以下配置:

假设使用的是本地事务(jdbc事务)

<property name="hibernate.current_session_context_class">thread</property>

假设使用的是全局事务(jta事务)

<property name="hibernate.current_session_context_class">jta</property>

假设採用的时Hibernate4,使用getCurrentSession()必须配置事务。否则无法取到session

 

 

 

3 hibernateTemplate.getSessionFactory().getCurrentSession()

我们使用springhibernate结合。操作数据库最经常使用可能是HibernateTemplateHibernateTemplate中集成了非常多使用的方法,可惜的是没的createQuery方法,或许我们使用hibernate的时候喜欢使用Query,我们可能会封装hibernateTemplate.getSessionFactory().getCurrentSession()方法得到Sessionsession创建Query。这是一个方法,但你应该会得到异常 “createQuery without an active transaction”,由于使用hibernateTemplate.getSessionFactory().getCurrentSession(),你是使用的hibernate的事务管理,而你指望spring管理的事务是hibernateTemplate,所以你会提示没有打开事务的异常,解决方法:1)使用hibernate事务处理。就像上面单独使用hibernate一样,但这或许不是你想要的。2)使用hibernateTemplateHibernateCallBack回调:

 

 

 

使用Hibernate的大多数应用程序须要某种形式的上下文相关的” session。特定的session在整个特定的上下文范围内始终有效。

然而,对不同类型的应用程序而言,要为什么是组成这种上下文下一个定义通常 是困难的。不同的上下文对当前这个概念定义了不同的范围。在3.0版本号之前。使用Hibernate的程序要么採用自行编写的基于 ThreadLocal的上下文session,要么採用HibernateUtil这种辅助类,要么採用第三方框架(比方SpringPico), 它们提供了基于代理(proxy)或者基于拦截器(interception)的上下文相关session 

3.0.1版本号开 始,Hibernate添加了SessionFactory.getCurrentSession()方法。一開始。它假定了採用JTA事务,JTA事务 定义了当前session的范围和上下文(scope and context)Hibernate开发团队坚信,由于有好几个独立的JTA TransactionManager实现稳定可用,不论是否被部署到一个J2EE容器中。大多数(假若不是全部的)应用程序都应该採用JTA事务管理。

 基于这一点,採用JTA的上下文相关session能够满足你一切须要。 

更好的是。从3.1开 始。SessionFactory.getCurrentSession()的后台实现是可拔插的。因此。我们引入了新的扩展接口 (org.hibernate.context.CurrentSessionContext)和新的配置參数 (hibernate.current_session_context_class)。以便对什么是当前session”的范围和上下文(scope and context)的定义进行拔插。

 

 

 

 

 

Hibernate4 No Session found for current thread原因 一号门-程序猿的工作,程序猿的生活(java,python,delphi实战).htm

Spring整合hibernate4:事务管理.htm

getCurrentSession 与 openSession() 的差别 - LoveYouT的专栏 博客频道 - CSDN.NET.htm

 

atitit.spring hibernate的事务机制 spring不能保存对象的解决

标签:3.0   保存   upd   rgb   事务管理   lov   .net   配置   好的   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/6897180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!