|
| 1 | +package com.ipman.springboot.transactional.sample; |
| 2 | + |
| 3 | +import com.ipman.springboot.transactional.sample.common.domain.model.User1; |
| 4 | +import com.ipman.springboot.transactional.sample.common.domain.model.User2; |
| 5 | +import com.ipman.springboot.transactional.sample.core.service.User1Service; |
| 6 | +import com.ipman.springboot.transactional.sample.core.service.User2Service; |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | +import org.springframework.beans.factory.annotation.Autowired; |
| 9 | +import org.springframework.boot.test.context.SpringBootTest; |
| 10 | + |
| 11 | +@SpringBootTest |
| 12 | +class TransactionPropagationTest { |
| 13 | + |
| 14 | + @Autowired |
| 15 | + private User1Service user1Service; |
| 16 | + |
| 17 | + @Autowired |
| 18 | + private User2Service user2Service; |
| 19 | + |
| 20 | + /** |
| 21 | + * Propagation.REQUIRED |
| 22 | + * 如果当前没有事务,就创建一个事务 |
| 23 | + * 如果已经存在一个事务中,加入这个事务中 |
| 24 | + * 总结: |
| 25 | + * 外围方法没有开启事务,插入"张三"、"李四"方法在自己事务中独立运行 |
| 26 | + * 外围方法异常不影响内部插入"张三"、"李四"方法独立的事务 |
| 27 | + */ |
| 28 | + @Test |
| 29 | + public void transactionPropagationRequired() { |
| 30 | + User1 user1 = new User1(); |
| 31 | + user1.setName("张三"); |
| 32 | + user1Service.addRequired(user1); |
| 33 | + |
| 34 | + User2 user2 = new User2(); |
| 35 | + user2.setName("李四"); |
| 36 | + user2Service.addRequired(user2); |
| 37 | + |
| 38 | + throw new RuntimeException(); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Propagation.REQUIRED |
| 43 | + * 如果当前没有事务,就创建一个事务 |
| 44 | + * 如果已经存在一个事务中,加入这个事务中 |
| 45 | + * 总结: |
| 46 | + * 外围方法没有开启事务,插入"张三"、"李四"方法在自己事务中独立运行 |
| 47 | + * 所以插入"李四"方法抛出异常只会回滚插入"李四"的方法,插入"张三"的方法不受影响 |
| 48 | + */ |
| 49 | + @Test |
| 50 | + public void transactionPropagationRequiredException() { |
| 51 | + User1 user1 = new User1(); |
| 52 | + user1.setName("张三"); |
| 53 | + user1Service.addRequired(user1); |
| 54 | + |
| 55 | + User2 user2 = new User2(); |
| 56 | + user2.setName("李四"); |
| 57 | + user2Service.addRequiredException(user2); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments