atitit.spring hibernate的事务机制 spring不能保存对象的解决
atitit.spring?hibernate的事務機制?spring不能保存對象的解決
?
sessionFactory.openSession()
不能。。log黑頭馬sql語言..
?
?
?
sessionFactory.getCurrentSession().update(user);
中間走ok蘭..log黑頭也有累..
?
?
在Spring中使用Hibernate,如果我們配置了TransactionManager,那么我們就不應該調用SessionFactory的openSession()來獲得Sessioin,因為這樣獲得的Session并沒有被事務管理。
?
作者::?老哇的爪子?Attilax?艾龍,??EMAIL:1466519819@qq.com
轉載請注明來源:?http://blog.csdn.net/attilax
?
?
采用getCurrentSession()創建的session會綁定到當前線程中,而采用openSession()創建的session則不會。
采用getCurrentSession()創建的session在commit或rollback時會自動關閉,而采用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()
我們使用spring和hibernate結合,操作數據庫最常用可能是HibernateTemplate,HibernateTemplate中集成了很多使用的方法,可惜的是沒的createQuery方法,也許我們使用hibernate的時候喜歡使用Query,我們可能會封裝hibernateTemplate.getSessionFactory().getCurrentSession()方法得到Session,session創建Query,這是一個方法,但你應該會得到異常?“createQuery?without?an?active?transaction”,因為使用hibernateTemplate.getSessionFactory().getCurrentSession(),你是使用的hibernate的事務管理,而你指望spring管理的事務是hibernateTemplate,所以你會提示沒有打開事務的異常,解決方法:1)使用hibernate事務處理,就像上面單獨使用hibernate一樣,但這也許不是你想要的。2)使用hibernateTemplate的HibernateCallBack回調:
?
?
?
使用Hibernate的大多數應用程序需要某種形式的“上下文相關的”?session,特定的session在整個特定的上下文范圍內始終有效。然而,對不同類型的應用程序而言,要為什么是組成這種“上下文”下一個定義通常?是困難的;不同的上下文對“當前”這個概念定義了不同的范圍。在3.0版本之前,使用Hibernate的程序要么采用自行編寫的基于?ThreadLocal的上下文session,要么采用HibernateUtil這樣的輔助類,要么采用第三方框架(比如Spring或Pico),?它們提供了基于代理(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不能保存对象的解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到掉牙齿出血是什么意思
- 下一篇: 【Oracle】锁表查询与解锁