文章目录
一、Spring 的事务管理
在学习 Spring 的时候,一般都是从 Ioc 容器开始学起,学了很长时间了,我就大概记得有这些内容:Ioc (控制反转)以及DI (依赖注入)、SpringAop切面编程、事务管理。
二、PlatformTransactionManager - - - 事务管理平台
1、getTransaction() 获取一个事务
2、commit() 提交事务
3、rollback() 回滚事务
1、TransactionDefinition 对事务进行描述
2、TransactionStatus 事务的状态
三、事务管理方式有两种:
1、编程式事务管理:通过代码编写事务
例如:权限判断
2、声明式事务管理:使用AOP实现事务的操作
例如:事务回滚
基于XML方式声明式事务(推荐:和AOP一起使用)
配置事务管理器
<!-- 1、配置事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
编写事务的通知
<!-- 2、编写通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 该规则是程序员根据自己项目中的事务规则,进行自行配置 -->
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
<tx:method name="del*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
<tx:method name="moditfy*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
<tx:method name="get*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true"/>
<tx:method name="query*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
</tx:attributes>
</tx:advice>
设置事务的切面以及切入点
<!-- 3、编写AOP配置声明式事务 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut expression="execution(* com.systop.jdbc.service.*.*(..))" id="txPointCut"/>
<!-- 切面的配置 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
基于annotation方式声明式事务
配置事务管理器
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
注解式声明事务
<!-- 注解式事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
使用注解,进行事务处理
@Transactional(propagation=Propagation.REQUIRED)
public void transfer(String outName, String inName, int money) {
userDao.out(outName, money);
userDao.in(inName, money);
}