事务的传播行为解析(Transaction propagation: Required,RequiresNew,Nested)

Posted yanyuechao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了事务的传播行为解析(Transaction propagation: Required,RequiresNew,Nested)相关的知识,希望对你有一定的参考价值。

propagation

1.Required

技术图片

 

//deviceService外部事务Propagation.required
@Transactional(rollbackFor = Throwable.class)
public void updateDeviceStatus(String string) {
	deviceMapper.updateDeviceStatus("20b5273ebeb84229a8c1e0d8b535974f", string);
	try {
		nestService.updateDeviceStatus("869aab5ad135491c95b90772d864034a", string);
	} catch (Exception e) {
		log.error("error", e);
	}
}

  

//nestService内部事务
@Transactional(propagation = Propagation.REQUIRED)
public void updateDeviceStatus(String s, String string) {
	deviceMapper.updateDeviceStatus(s, string);
	int i = 1 / 0;
}

  

1.1,外部方法有事务注解 且 传播行为是propagation.required ,也有事务注解 且 传播行为是propagation.required。当内部方法或外部方法出现抛出异常时,无论外部方法是否捕获异常,内外事务都会回滚;

1.2,外部方法没有事务注解 , 内部方法也有事务注解且传播行为是propagation.required,当内部方法出现抛出异常时。无论外部方法是否捕获异常,只有内部方法回滚事务;

1.3,外部方法有事务注解且传播行为是propagation.required,内部方法没有事务注解。当内部方法出现抛出异常时,外部捕获异常,内外事务都不会回滚;

1.4,外部方法有事务注解且传播行为是propagation.required,内部方法没有事务注解。当内部方法出现抛出异常时,外部不捕获异常,内外事务都会回滚;

 

2.requiresNew 

 技术图片

 

 

2.1,外部方法有事务注解且传播行为是propagation.required, 内部方法也有事务注解且传播行为是propagation.requiredNew。当内部方法出现抛出异常时,外部方法捕获异常,只有内事务会回滚;当内部方法抛出异常时,外部方法不捕获异常,那么内外事务都会回滚;

2.2,外部方法有事务注解 且 传播行为是propagation.required, 内部方法也有事务注解且传播行为是propagation.requiredNew。当外部方法出现抛出异常时,只有外部事务会回滚;

3. Nested

 

PROPAGATION_NESTED is different again in that it uses a single physical transaction with multiple savepoints that it can roll back to. Such partial rollbacks allow an inner transaction scope to trigger a rollback for its scope, with the outer transaction being able to continue the physical transaction despite some operations having been rolled back. This is typically mapped onto JDBC savepoints, so will only work with JDBC resource transactions

 3.1,外部方法有事务注解且传播行为是propagation.required , 内部方法也有事务注解且传播行为是propagation.nested。当内部方法出现抛出异常时,外部方法捕获异常,只有内事务会回滚;当内部方法抛出异常时,外部方法不捕获异常,那么内外事务都会回滚;

3.2,外部方法有事务注解且传播行为是propagation.required , 内部方法也有事务注解且传播行为是propagation.nested。当外部方法出现抛出异常时,内外事务都会回滚;

 

Propagation.REQUIRED

quired , 内部方法也有事务注解 且 

以上是关于事务的传播行为解析(Transaction propagation: Required,RequiresNew,Nested)的主要内容,如果未能解决你的问题,请参考以下文章

浅析Spring事务传播行为和隔离级别

SpringBoot事务隔离等级和传播行为的那些事儿

重新理解mysql的锁事务隔离级别及事务传播行为

transaction2

Spring-事务原理解读

请解释Spring事务传播传播行为