Spring事务管理

Spring事务管理

1.两种方式

1.1方式一:结合springAOP实现事务管理
<!--控制事务需要连接对象,所以要连接jdbc的事务-->
	 <bean id="txMange" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	 		<property name="dataSource" ref="source"/>
	 </bean>
	
	 <tx:advice id="txAdvice" transaction-manager="txMange">
	 		<tx:attributes>
	 			<tx:method name="*"/>
	 		</tx:attributes>
	 </tx:advice>
	 
	 配置事务的切入点
	 <aop:config>
	 		<aop:pointcut expression="execution(* fyjz.com.spring.Service.UserServiceImpl.*(..))" id="txpoint"/>
	 		<!--advice-ref:配置事务的类-->
	 		<!--pointcut-ref:事务切入点-->
	 		<aop:advisor advice-ref="txAdvice" pointcut-ref="txpoint"/>
	 </aop:config>
	  
1.2方式二:注解方式

设置注解驱动的事务管理(启动事务管理让DataSourceTransactionManager来管理事务)

<tx:annotation-driven transaction-manager="txMange"/>

2.业务层转账事件

要求:用户1向用户2转账,1的钱数减少,2的钱数增加,将两个事件捆绑成一个事务,要么同时发生,要么都不发生。

	//转账
	@Transactional//事务注解
	public void trash(int idout,int idin,double money) {
		mapper.updateMoneyById(idout,money);
		mapper.updateMoneyById2(idin,money);
	}

3.持久层映射器(接口)

public interface UserMapper {
	
	
	//修改用户金额
	int updateMoneyById(@Param("id")int id,@Param("money")double money);
	
	//修改用户金额
	int updateMoneyById2(@Param("id")int id,@Param("money")double money);
	
	
}

4.持久层映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" 
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
 
 
 <!--映射文件(映射器的全名:包名.类名)-->
 <mapper namespace="fyjz.com.spring.Mapper.UserMapper">

 		<update id="updateMoneyById" >
 			update u_user set money=money-#{money} where id=#{id};
 		</update>
 		
 		<update id="updateMoneyById2" >
 			update u_user set money=money+#{money} where id=#{id};
 		</update>
 		
 		
 </mapper>
 	

5.Test测试

	@Test
	public void test01(){
		service.trash(1, 2, 1000);
	}

用户1向用户2转账1000元

转账前:
在这里插入图片描述
转账后:
在这里插入图片描述
转账成功

如果两个事件有一个事件发生错误,无法正常执行,则如,
在这里插入图片描述
则这个事务将无法执行,如下图:

代码运行出错,表的两个数据都没有改变,还是原来的样子,在现实生活中,最常见的就是银行信用卡的使用了。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值