事务作用:在数据层保障一系列的数据库操作同成功同失败
Spring事务作用:在数据层或业务层保障一系列的数据库操作同成功同失败
需求:实现任意两个账户间转账操作
结果分析:
首先来看样例:
在spring的整体大框架中,实例代码的结构如图所示:
再来看数据库表中两个人的账户余额:
正常情况下将老王的钱转账500给张三
package com.Alvis;
import com.Alvis.config.SpringConfig;
import com.Alvis.service.FundsService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class ServiceTest {
@Test // 测试转账方法
public void transferMoney() {
ApplicationContext apc = new AnnotationConfigApplicationContext(SpringConfig.class);
FundsService fundsService = apc.getBean(FundsService.class);
fundsService.transfer(500);
}
}
================================================
转帐前:
Property{id=1, name='老王', property=1000}
Property{id=2, name='张三', property=1000}
转账后:
Property{id=1, name='老王', property=500}
Property{id=2, name='张三', property=1500}
进程已结束,退出代码0
但是如果程序中出错,就会只执行了老王转账的操作,并没有执行张三收钱的操作:
执行后的结果为:
解决办法:进行事务管理:(三步走)
第一步:在SpringConfig中注解开启事务,告诉Spring有事务需要开启:
第二步:在接口注解需要开启事务的方法:
第三步:在JdbcConfig中对事务管理的第三方的配置进行bean管理,具体来说就是创建新的Bean:
加上事务管理之后再次运行程序:
同成功同失败!!!