1. 程式人生 > 實用技巧 >Spring中的宣告式事務

Spring中的宣告式事務

13、Spring事務

1、回顧事務

  • 把一組業務當成一個業務來做;要麼都成功,要麼都失敗!
  • 事務在專案開發中,十分的重要,涉及到資料的一致性問題,不能馬虎!
  • 確保完整性和一致性;

事務ACID原則:

  • 原子性
  • 一致性
  • 隔離性
    • 多個業務可能操作同一個資源,防止資料損壞
  • 永續性
    • 事務一旦提交,無論系統發生什麼問題,結果都不會再被影響,被持久化的寫到儲存器中!

2、Spring中的事務管理

  • 宣告式事務:AOP
  • 程式設計式事務:需要在程式碼中,

1、在Spring容器中配置宣告式事務

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <constructor-arg ref="dataSource" />
</bean>

2、結合AOP,實現事務的織入

配置事務通知

<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <!--給那些方法配置事務-->
  <!--配置事務的傳播特性: new propagation= -->
  <tx:attributes>
    <tx:method name="add" propagation="REQUIRED"/>
    <tx:method name="delete" propagation="REQUIRED"/>
    <tx:method name="update" propagation="REQUIRED"/>
    <tx:method name="query" read-only="true"/>
    <tx:method name="*"  propagation="REQUIRED"/>
  </tx:attributes>
</tx:advice>

3、配置事務的切入

<!--配置事務切入-->
<aop:config>
  <aop:pointcut id="txPointCut" expression="execution(*com.qilu.mapper.*.*(..)"/>
  <aop:advisor advice-ref= "txAdvice" pointcut-ref="txPointCut"/>
</aop:config>