當前位置:編程學習大全網 - 編程語言 - 請教tomcat+spring+hibernate全局事務的有關問題

請教tomcat+spring+hibernate全局事務的有關問題

spring提供了對hibernate等pojo對象的事務管理的支持。這是壹個spring的壹個意義重大的特性。

spring提供兩種方式對hibernate提供事務管理方式,分別為編程式事務管理和聲明式事務管理。

spring事務策略,也就是spring事務管理的實現方式.它有壹個統壹的抽象是由實現下面這個接口完成的.org.springframework.transaction.PlatformTransactionManager.像我們常見到的HibernateTransactionManager也是實現的這個接口。

不管是聲明式的還是編程式的事務管理都需要此抽象來完成.

壹、編程式事務

編程式事務常用getCurrentSession和openSession來完成。

代碼片段

[java] view plain copy

public void addUser(User user) {

Sessionsession=null;

try{

session=HibernateUtils.getSessionFactory().getCurrentSession();

//或者session=HibernateUtils.getSessionFactory().openSession();

session.beginTransaction();

session.save(user);

Log log=new Log();

log.setType("caozuorizhi");

log.setTime(new Date());

log.setDetail("RIZHI");

LogManager logManager=newLogMangerImpl();

logManager.addLog(log);

session.getTransaction().commit();

}catch(Exception e){

e.printStackTrace();

session.getTransaction().rollback();

}

}

那麽這兩種方法openSession和getCurrentSession有什麽區別呢?

(1)、openSession必須關閉,currentSession在事務結束後自動關閉

openSession沒有和當前線程綁定,currentSession和當前線程綁定,即在壹個線程中是同壹個Session。而OpenSession每次用到的都不是同壹個,所以用完後需要關閉。

(2)、如果使用currentSession需要在hibernate.cfg.xml文件中進行配置:

* 如果是本地事務(jdbc事務)

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

* 如果是全局事務(jta事務)

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

  • 上一篇:跪求,單片機程序註釋
  • 下一篇:山東濱州劍橋學院最新招生簡章?
  • copyright 2024編程學習大全網