一、前置知识
1、Java异常中,Throwable是最顶层的父类,有Error和Exception两个子类
2、Exception分为运行时异常(RuntimeException及其子类)和非运行时异常(Exception子类中,除了RuntimeException及其子类之外的类)
3、使用spring的@Transactiona开启事务,默认Error和RuntimeException及其子类才会回滚
4、@Transactiona默认传播行为是REQUIRED,需要配合其他传播行为测试,请查看:Spring事务传播行为实战
二、情况
1、遇到异常回滚
- Error和RuntimeException及其子类的异常
// 回滚
@Transactional
public void add() {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
throw new RuntimeException("运行报错啦");
// throw new OutOfMemoryError();
}
- 非运行时异常
// 不回滚
@Transactional
public void add2() throws IOException {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
throw new IOException();
}
2、捕获异常后不回滚
@Transactional
public void add() {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
try {
throw new RuntimeException("运行报错啦");
} catch (RuntimeException e) {
e.printStackTrace();
}
}
3、指定异常才回滚
// 回滚
@Transactional(rollbackFor = NullPointerException.class)
public void add() {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
int forlan = 1 / 0;
}
分析说明:这里虽然抛出的是ArithmeticException,但我们指定是NullPointerException才会回滚,为什么还是回滚了呢?
其实这两个类都是继承RuntimeException,Spring本来就默认了RuntimeException子类也是回滚的
rollbackFor参数,针对的是非运行时异常,实现一个追加拓展
// 回滚
@Transactional(rollbackFor = IOException.class)
public void add2() throws IOException {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
throw new IOException();
}
4、指定异常不回滚
// 不回滚
@Transactional(noRollbackFor = ArithmeticException.class)
public void add2() {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
int forlan = 1 / 0;
}
5、指定部分代码回滚
// ks_a表数据插入成功,ks_b数据回滚
@Transactional
public void add3() {
KsA ksA = new KsA();
ksA.setName("林");
ksAService.insert(ksA);
Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
try {
KsB ksB = new KsB();
ksB.setAge(10);
ksBService.insert(ksB);
throw new RuntimeException("父方法报错");
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);
}
}
标签:实战,insert,回滚,RuntimeException,事务,KsA,new,ksA
From: https://www.cnblogs.com/huozhonghun/p/16900488.html