1. 程式人生 > >atitit.spring hibernate的事務機制 spring不能保存對象的解決

atitit.spring hibernate的事務機制 spring不能保存對象的解決

pda 程序 oca roman 配置 轉載 post 本地事務 對象

atitit.spring hibernate的事務機制 spring不能保存對象的解決

sessionFactory.openSession()

不能。

log黑頭馬sql語言..

sessionFactory.getCurrentSession().update(user);

中間走ok..log黑頭也有累..

Spring中使用Hibernate。假設我們配置了TransactionManager。那麽我們就不應該調用SessionFactoryopenSession()來獲得Sessioin。由於這樣獲得的Session並沒有被事務管理。

作者:: 老哇的爪子 Attilax 艾龍, EMAIL:[email protected]

轉載請註明來源: 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不能保存對象的解決