Spring transaction: rollback on Exception or Throwable

前端 未结 4 2201
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 08:26

I wonder whether it makes sense to use instead of

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

to use

4条回答
  •  旧时难觅i
    2020-12-05 08:44

    As I understand catching Error will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?

    You don't need to explicitly specify rollbackFor = Throwable.class, because spring will by default rollback the transaction if an Error occurs.

    See 12.5.3 Rolling back a declarative transaction

    In its default configuration, the Spring Framework's transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. (Errors will also - by default - result in a rollback). Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.

    Or take a look at the DefaultTransactionAttribute

    public boolean rollbackOn(Throwable ex) {
        return (ex instanceof RuntimeException || ex instanceof Error);
    }
    

提交回复
热议问题