Spring的事务管理

一、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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值