前言
? ? 我们都知道@Transactional在一些场景下会失效,这些场景我们要记下,哪天报了个bug可能就是事务干的。事务的开始从@Transactional开始,Spring使用AOP面向切面编程,底层用ThreadLocal保证在同一个事务中。下面用SpringBoot+MyBatis-plus结构讲解:
被测试类protected方法:
@Service
public class SecKillServiceImpl extends ServiceImpl<SecKillMapper, SecKill> implements SecKillService {
@Autowired
private SignLogService signLogService;
@Transactional(rollbackFor = Exception.class)
protected void insert() {
insertLog();
addKill();
}
private void insertLog() {
signLogService.addSign();
}
private void addKill() {
SecKill secKill = new SecKill();
secKill.setUserId(1314L);
//baseMapper.insert(secKill);
int i = 10/0; // 模拟异常
}
}
@Override
public void addSign() {
SignLog signLog = new SignLog();
signLog.setId("1314520");
signLog.setCrtTime(LocalDate.now());
signLog.setPoint(11314520);
signLog.setSignId("sign");
signLog.setType(1);
signLog.setUserId("admin");
baseMapper.insert(signLog);
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SecKillServiceImplTest {
@Autowired
private SignLogService signLogService;
@Autowired
private SecKillServiceImpl secKillServiceImpl;
@Test
public void dod() {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>"+signLogService.list());
}
@Test
public void add() {
secKillServiceImpl.insert();
}
}
测试结果:
抛异常数据库记录没有回滚:
被测试类public方法:
@Service
public class SecKillServiceImpl extends ServiceImpl<SecKillMapper, SecKill> implements SecKillService {
@Autowired
private SignLogService signLogService;
@Transactional(rollbackFor = Exception.class)
public void insert() {
insertLog();
addKill();
}
private void insertLog() {
signLogService.addSign();
}
private void addKill() {
SecKill secKill = new SecKill();
secKill.setUserId(1314L);
//baseMapper.insert(secKill);
int i = 10/0; // 模拟异常
}
}
测试类同上
测试结果:
?抛异常回滚数据库无记录:
|