1 多线程操作数据库的问题(事务配置采用spring默认策略)
主线程中开启一个子线程,如果子线程出现异常的话,子线程会回滚吗?主线程会回滚吗?
案例:
@Service
@Transactional
public class PayService implements IPayService {
@Autowired
private PayMapper payMapper;
@Autowired
private AccountMapper accountMapper;
private Executor executor = Executors.newSingleThreadExecutor();
@Override
public Integer testTransactionThread(Pay pay) {
int insert = payMapper.insert(pay);
Long id = pay.getId();
executor.execute(() -> {
Account account = new Account();
account.setId(id);
accountMapper.insert(account);
if (id == 2) {
throw new RuntimeException("模拟异常");
}
});
return insert;
}
}
结果:
Exception in thread "pool-2-thread-1" java.lang.RuntimeException: 模拟异常
at com.example.service.impl.PayService