Spring 事务在 RuntimeException 上回滚

问题描述 投票:0回答:1

我有一个事务方法,我想调用另一个可能抛出 RuntimeException 的方法。

问题在于,仅当抛出异常时,事务才会被标记为回滚。

另一个方法调用本身位于 try-catch 块中,但我认为当另一个方法通过抛出异常返回时,事务会被标记。

示例:

MyService.java

@Service
public class MyService {

    @Autowired
    private MyUtils utils;

    @Autowired
    private MyCrudRepository repository;

    @Transactional
    public void publicMethod() {
       try {
           utils.otherPublicMethod();
       } catch (Exception ex) {
           ex.printStackTrace();
       }

       // RollbackException: Transaction marked as rollbackOnly
       // Even though I caught the exception from the method call itself
       repository.save(new MyEntity());
    }
}

MyUtils.java

@Component
public class MyUtils {

    // Does not use transactions, repositories
    // But I think it inherits the transaction and marks it as rollbackOnly
    public void otherPublicMethod() {

        // Maybe this is seen as an uncaught exception
        throw new RuntimeException();
    }
}

编辑:

我不认为这是重复的Does Specificing @Transactional rollbackFor Also Include RuntimeException,因为异常最终会被捕获。
问题可能是类似的,因为它也涉及事务和回滚。

java spring spring-boot exception spring-transactions
1个回答
0
投票

注释

@Transactional
具有诸如
rollbackFor
no-rollback-for
之类的参数,您可以使用它们来说明哪些异常会导致或不会导致回滚。例如你可以写:

@Transactional(rollbackFor = {RuntimeException.class})

这将导致

RuntimeException
时回滚。但是,我相信
RuntimeException
默认会导致回滚。因此,您可能必须在
no-rollback-for
子句中指定此异常。 有关详细信息,请参阅交易管理并查找“16.5.5设置”段落

© www.soinside.com 2019 - 2024. All rights reserved.