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元
转账前:
转账后:
转账成功
如果两个事件有一个事件发生错误,无法正常执行,则如,
则这个事务将无法执行,如下图:
代码运行出错,表的两个数据都没有改变,还是原来的样子,在现实生活中,最常见的就是银行信用卡的使用了。