首页 > 解决方案 > Spring @Transactional 不适用于 CompletableFuture

问题描述

@Transactional(rollbackFor = Exception.class)
public void test(){
    CompletableFuture cf1 = CompletableFuture.runAsync(()-> dbMapper.insert());

    CompletableFuture cf2 = CompletableFuture.runAsync(()->{
        dbMapper.insert();
        throw new RuntimeException();
    });
    CompletableFuture.allOf(cf1, cf2).join(); // this will throw CompletionException
}

在上面的代码中,我想在抛出任何异常时回滚insert()操作。但实际上没有回滚发生。cf1cf2join()

如何使它工作?或者还有其他方法吗?

标签: javaspringspring-bootspring-transactionscompletable-future

解决方案


推荐阅读