13、声明式事务

AnJiaYu / 2023-08-27 / 原文

13、声明式事务

13.1、回顾事务

  • 要么都成功,要么都失败

  • 事务在开发种十分的重要,设计到数据一致性的问题,非常的重要

  • 确保完整性和一致性

事务的ACID原则

  1. 原子性

  2. 一致性

  3. 隔离性:多个业务操作同一个资源,防止数据损坏

  4. 持久性:事务一旦提交,无论系统出现什么问题,结果都不会受到影响,被持久化到存储器中

13.2、Spring中的事务管理

  • 声明式事务AOP

  • 编程式事务

     

标准配置

要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager 对象:

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

配置事务通知

<!--    配置事务通知-->
<!-- 配置事务的传播特性-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<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>

AOP切入事务

<aop:config>
   <aop:pointcut id="txPointCut" expression="execution(* com.an.mapper.*.*(..))"/>
   <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"></aop:advisor>
</aop:config>