1 代码实现
1.1 正常情况
我们采用手动开启事务的方式
public void add(CountDownLatch countDownLatch) {
executor.submit(() -> {
TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
try {
ThreadTest obj = new ThreadTest();
obj.setColumnName("threadTest");
log.info("开始插入");
threadTestMapper.insert(obj);
countDownLatch.countDown();
// throw new RuntimeException("故意抛出错误测试是否会进行回滚");
} catch (Exception e) {
log.info("出现异常了开始回滚");
dataSourceTransactionManager.rollback(transaction);
} finally {
dataSourceTransactionManager.commit(transaction);
}
});
}
insert方法中插入100条测试数据到数据库,通过手动开启事务的方式在每个子线程中开启各自的事务。注意注释的位置,首先测试没有错误的情况。
完整代码
@Service
@RequiredArgsConstructor
@Slf4j
public