- 事務———把一些操作放在一起處理,要麼全部成功,要麼全部失敗。
在這裏我們介紹一下ssh整合的時候,事務的使用和管理。
這是聲明事務管理,所以不需要寫代碼,只需要在 applicationContext.xml 文件中配置一下就行了。
第一步:聲明命名空間
xmlns:aop=”http://www.springframework.org/schema/aop”
xmlns:tx=”http://www.springframework.org/schema/tx”
xsi:schemaLocation=“http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd”
切記,這些 命名空間是有順序的呦。
第二步:聲明一個事務管理器,並把它命名爲 id=“”,class=“”是所在類的路徑
<bean id = "HibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
第三步:聲明事務通知,id是自己命名的名字,transaction-manager聲明一個爲HibernateTransactionManager的代理類。tx:attributes是事務的範圍限定,tx:method name=”xx*” propagation=”REQUIRED,以xx開始的方法都要放在事務裏面。tx:method name=”login*” propagation=”SUPPORTS read-only=”true” 表示有事務了放在事務裏邊,並標記爲只讀,沒事務就不在管理。
<!-- 事務通知 -->
<tx:advice id="txAdvice" transaction-manager="HibernateTransactionManager">
<tx:attributes>
<!-- 必須放在事務裏邊的 -->
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<!-- 有事務放在事務裏,並標記爲只讀,沒事務就不放在事務裏 -->
<tx:method name="login*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
- 下面附上完整分代碼
<!-- 事務管理器 -->
<bean id = "HibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事務通知 -->
<tx:advice id="txAdvice" transaction-manager="HibernateTransactionManager">
<tx:attributes>
<!-- 必須放在事務裏邊的 -->
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<!-- 有事務放在事務裏,並標記爲只讀,沒事務就不放在事務裏 -->
<tx:method name="login*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="bizAop" expression="execution(* com.jfl.biz.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="bizAop" />
</aop:config>