瘋狂

          STANDING ON THE SHOULDERS OF GIANTS
          posts - 481, comments - 486, trackbacks - 0, articles - 1
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          hibernate spring 事務

          Posted on 2009-08-31 16:39 瘋狂 閱讀(1679) 評論(0)  編輯  收藏 所屬分類: springhibernate

           

          在我們的項目中我們可以使用spring的事務機制來處理,以此來節省工作量,一下就例子來討論下:

          實例:

          采用spring2.x版本:hibenate3.x

          首先:

          看sessionfactory的配置,我們使用hibenate的sessionfactory配置:

          <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" default-autowire="byName" default-lazy-init="true"> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">----//在此由于我使用的是annoation形式的po 如果配置其他將不能持久化 <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean>></beans>

           

           

          
          

           

           當然也可以使用spring的datasource來配置,也就是使用:org.springframework.jdbc.datasource.DriverManagerDataSource,自我感覺這樣分開比較好

           hibernate.cfg.xml:

          <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.url"> jdbc:mysql://localhost:3306/hbman </property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="hibernate.show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> <property name="cache.use_second_level_cache">false</property> <property name="cache.use_query_cache">false</property> <property name="connection.isolation">2</property> <mapping class="com.po.A" /> </session-factory> </hibernate-configuration>

           

           

          
          

           

           

           我們的po類class A(使用hibenate anoation)

           

          package com.po; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Version; @Entity public class A { private int id; private int anum; private String aname; private int version; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Version public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } ....get set.. }

           

           

          
          

           

           dao:

           

          public class Dao extends HibernateDaoSupport { public Serializable save(Object entity){ return getHibernateTemplate().save(entity); } }

           

           

          
          

           

          測試server:我們在兩個需要事物處理的調用之間拋出異常:

          public class TestSH { private Dao dao; public void save() throws MyE{ A a = new A(); a.setAname("aname"); a.setAnum(1); dao.save(a); if(true){ throw new MyE("************異常*************"); } A a1 = new A(); a1.setAname("aname1"); a1.setAnum(1); dao.save(a1); }..get set...

           

           

          
          

           

           在這說明需要拋出RuntimeException(或者子類)或者Exception的子類,如果拋出Exception將spring將不能對他進行自動回滾,需要我們在文件中配置,如下:

          <tx:.... rollback-for="java.lang.Exception"/>//也就是spring所謂的 Winning rollback rule

          事務配置:

          <tx:advice id="txAdviceService" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="load*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="list*" read-only="true"/> <tx:method name="check*" read-only="true"/> <tx:method name="browse*" read-only="true"/> <tx:method name="search*" read-only="true"/> <tx:method name="*" read-only="false" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="actionMethods" expression="execution(* com.action.*.*(..))"/> <aop:advisor advice-ref="txAdviceService" pointcut-ref="actionMethods"/> </aop:config> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean>

           

           

          
          

           

           

           測試配置如下:

          <bean id="dao" class="com.server.Dao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="test" class="com.action.TestSH"> <property name="dao" ref="dao"></property> </bean>

           

           

          
          

           

           說明: 需要自動事務的類必須是spring可加載的也就是需要在文件中配,否則就會出現事務不起作用的情況 具體的討論文章可見javaeye上

           

           

           測試類:

          public class Test { private static TestSH testsh; static{ System.out.println("init....."); ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"applicationContext-*.xml","applicationContext.xml"}); testsh = (TestSH) ctx.getBean("test"); } public static void main(String[] args) { try { testsh.save(); } catch (MyE e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

           

           

          
          

           

           最終控制臺信息:

          09-08-31 16:52:06,187 DEBUG (org.springframework.transaction.interceptor.TransactionInterceptor:282) - Getting transaction for [com.action.TestSH.save] 2009-08-31 16:52:06,187 DEBUG (org.springframework.transaction.support.TransactionSynchronizationManager:140) - Retrieved value [org.springframework.orm.hibernate3.SessionHolder@191e4c] for key [org.hibernate.impl.SessionFactoryImpl@11415c8] bound to thread [main] 2009-08-31 16:52:06,187 DEBUG (org.springframework.transaction.support.TransactionSynchronizationManager:140) - Retrieved value [org.springframework.orm.hibernate3.SessionHolder@191e4c] for key [org.hibernate.impl.SessionFactoryImpl@11415c8] bound to thread [main] 2009-08-31 16:52:06,187 DEBUG (org.springframework.orm.hibernate3.HibernateTemplate:364) - Found thread-bound Session for HibernateTemplate Hibernate: insert into A (aname, anum, version) values (?, ?, ?) 2009-08-31 16:52:06,234 DEBUG (org.springframework.orm.hibernate3.HibernateTemplate:388) - Not closing pre-bound Hibernate Session after HibernateTemplate 2009-08-31 16:52:16,234 DEBUG (org.springframework.transaction.interceptor.TransactionInterceptor:327) - Completing transaction for [com.action.TestSH.save] after exception: com.exc.MyE: ************異常************* 2009-08-31 16:52:16,234 DEBUG (org.springframework.transaction.interceptor.RuleBasedTransactionAttribute:130) - Applying rules to determine whether transaction should rollback on com.exc.MyE: ************異常************* 2009-08-31 16:52:16,234 DEBUG (org.springframework.transaction.interceptor.RuleBasedTransactionAttribute:148) - Winning rollback rule is: RollbackRuleAttribute with pattern [java.lang.Exception] 2009-08-31 16:52:16,234 DEBUG (org.springframework.orm.hibernate3.HibernateTransactionManager:846) - Triggering beforeCompletion synchronization 2009-08-31 16:52:16,234 DEBUG (org.springframework.orm.hibernate3.HibernateTransactionManager:751) - Initiating transaction rollback 2009-08-31 16:52:16,234 DEBUG (org.springframework.orm.hibernate3.HibernateTransactionManager:593) - Rolling back Hibernate transaction on Session [org.hibernate.impl.SessionImpl@4298e] 2009-08-31 16:52:16,265 DEBUG (org.springframework.orm.hibernate3.HibernateTransactionManager:875) - Triggering afterCompletion synchronization 2009-08-31 16:52:16,265 DEBUG (org.springframework.transaction.support.TransactionSynchronizationManager:276) - Clearing transaction synchronization 2009-08-31 16:52:16,265 DEBUG (org.springframework.transaction.support.TransactionSynchronizationManager:193) - Removed value [org.springframework.orm.hibernate3.SessionHolder@191e4c] for key [org.hibernate.impl.SessionFactoryImpl@11415c8] from thread [main] 2009-08-31 16:52:16,265 DEBUG (org.springframework.orm.hibernate3.HibernateTransactionManager:653) - Closing Hibernate Session [org.hibernate.impl.SessionImpl@4298e] after transaction 2009-08-31 16:52:16,265 DEBUG (org.springframework.orm.hibernate3.SessionFactoryUtils:771) - Closing Hibernate Session com.exc.MyE: ************異常************* at com.action.TestSH.save(TestSH.java:29)

           

           

          
          

           

           另外針對事務配置可以在最外層的業務層設置,防止嵌套獲取事務的情況(當然不會出現實務問題)。

           



          主站蜘蛛池模板: 达孜县| 黎城县| 利辛县| 白山市| 武安市| 穆棱市| 柳江县| 淄博市| 西乌珠穆沁旗| 上蔡县| 东山县| 镇安县| 龙井市| 宾阳县| 小金县| 广河县| 北辰区| 扶余县| 睢宁县| 怀宁县| 建瓯市| 汝州市| 鹤峰县| 定陶县| 瑞昌市| 黎城县| 平遥县| 安塞县| 灵川县| 平塘县| 诏安县| 长阳| 洛扎县| 怀远县| 湾仔区| 安义县| 彭山县| 基隆市| 交城县| 新龙县| 白沙|