Skip to content

Commit 5a44269

Browse files
authored
spring 事务 PROPAGATION_NESTED纠错
ROPAGATION_NESTED:如果当前存在事务,就在嵌套事务内执行;如果当前没有事务,就执行与PROPAGATION_REQUIRED类似的操作,子事务回滚外部主事务也会受到影响进行回滚 ``` @service public class UserInvokeService { @Autowired private UserService userService; @resource private UserMapper userMapper; @transactional public void invokeUserService() { User user = new User(); user.setName("zxx"); user.setAge(333333); userMapper.insert(user); userService.insertData(); } } @service public class UserService { @resource private UserMapper userMapper; @transactional(propagation = Propagation.NESTED) public void insertData() { User user = new User(); user.setName("inserByNested"); user.setAge(2222); userMapper.insert(user); int a = 1 / 0; } } @SpringBootTest public class TransactionalTest { @Autowired UserService userService; @Autowired UserInvokeService userInvokeService; @test public void testTransaction() { userInvokeService.invokeUserService(); } } ```
1 parent 15c9291 commit 5a44269

File tree

1 file changed

+4
-11
lines changed

1 file changed

+4
-11
lines changed

docs/system-design/framework/spring/spring-transaction.md

+4-11
Original file line numberDiff line numberDiff line change
@@ -393,14 +393,13 @@ Class B {
393393

394394
**3.`TransactionDefinition.PROPAGATION_NESTED`**:
395395

396-
如果当前存在事务,则创建一个事务作为当前事务的嵌套事务来运行;如果当前没有事务,则该取值等价于`TransactionDefinition.PROPAGATION_REQUIRED`。也就是说:
397-
398-
1. 在外部方法未开启事务的情况下`Propagation.NESTED``Propagation.REQUIRED`作用相同,修饰的内部方法都会新开启自己的事务,且开启的事务相互独立,互不干扰。
399-
2. 如果外部方法开启事务的话,`Propagation.NESTED`修饰的内部方法属于外部事务的子事务,外部主事务回滚的话,子事务也会回滚,而内部子事务可以单独回滚而不影响外部主事务和其他子事务。
396+
如果当前存在事务,就在嵌套事务内执行;如果当前没有事务,就执行与`TransactionDefinition.PROPAGATION_REQUIRED`类似的操作。也就是说:
400397

398+
1. 在外部方法开启事务的情况下,在内部开启一个新的事务,作为嵌套事务存在。
399+
2. 如果外部方法无事务,则单独开启一个事务与 PROPAGATION_REQUIRED 类似
401400
这里还是简单举个例子:
402401

403-
如果 `aMethod()` 回滚的话,`bMethod()``bMethod2()`都要回滚,而`bMethod()`回滚的话,并不会造成 `aMethod()``bMethod()2`回滚
402+
如果 `bMethod()` 回滚的话,`aMethod()`也会回滚
404403

405404
```java
406405
Class A {
@@ -409,7 +408,6 @@ Class A {
409408
//do something
410409
B b = new B();
411410
b.bMethod();
412-
b.bMethod2();
413411
}
414412
}
415413

@@ -418,12 +416,7 @@ Class B {
418416
public void bMethod {
419417
//do something
420418
}
421-
@Transactional(propagation=propagation.PROPAGATION_NESTED)
422-
public void bMethod2 {
423-
//do something
424-
}
425419
}
426-
```
427420

428421
**4.`TransactionDefinition.PROPAGATION_MANDATORY`**
429422

0 commit comments

Comments
 (0)