简体   繁体   English

Spring 启动:使用@Transactional 进行手动回滚

[英]Spring boot: do manual rollback with @Transactional

Is it possible to mix the transaction programmatic and annotation-based management?是否可以混合使用事务程序化和基于注释的管理? By default, @Transactional does a rollback on any Runtime and rethrows it.默认情况下,@Transactional 对任何运行时进行回滚并重新抛出它。

I would like to not rethrow it, but return Optional.empty() is it possible?我不想重新抛出它,但返回 Optional.empty() 是否可能? It is easy to implement with transaction programmatic management: (I took example from the Spring docs)使用事务编程管理很容易实现:(我以 Spring 文档为例)

transactionTemplate.execute(new TransactionCallbackWithoutResult() {

    protected (Optional<User>) doInTransactionWithoutResult(TransactionStatus status) {
        try {
            doStuff();
            return createUser();
        } catch (RuntimeException ex) {
            status.setRollbackOnly();
            return Optional.empty();
        }
    }
});

Is it possible to combine them in a good way?是否有可能以一种好的方式将它们结合起来? Lets say:让我们说:

@Transactional
Optional<User> manageUser() {
  try {
    doStuff();
    return createUser();
  } case (RuntimeException e) {
     SomeTransactionalClass.setRollbackOnly();
     return Optional.empty();
  }
}

And what do you think, is mixing 2 ways of managing transactions a code smell?你认为,混合两种管理事务的方式是一种代码味道吗?

Thanks you.谢谢。

First solution that bounced to my head was to handle it on the catch block and it's the same solution that you found.跳到我头上的第一个解决方案是在 catch 块上处理它,这与您找到的解决方案相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM