zoukankan      html  css  js  c++  java
  • atitit.spring hibernate的事务机制 spring不能保存对象的解决

    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

  • 相关阅读:
    Tiny64140之初始化时钟
    Tiny6410之控制icache驱动
    Tiny6410之按键裸机驱动
    Linux -- man 、info、 whatis、 -h
    Linux -- which whereis
    Linux -- sudoers (简单:转)
    Linux -- sudo
    Linux -- sudoers文件
    Linux -- cp
    Linux -- mv
  • 原文地址:https://www.cnblogs.com/attilax/p/5963714.html
Copyright © 2011-2022 走看看