Spring 事务:在 Exception 或 Throwable 上回滚 [英] Spring transaction: rollback on Exception or Throwable
问题描述
我想知道用
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
使用Throwable
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
据我所知,即使发生了非常糟糕的事情,捕捉 Error
也能帮助我们正确行事.或者也许它没有帮助?
As I understand catching Error
will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?
推荐答案
据我所知,即使发生了非常糟糕的事情,捕捉错误也会帮助我们正确行事.或者也许它没有帮助?
As I understand catching Error will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?
您不需要显式指定rollbackFor = Throwable.class
,因为如果发生Error
,spring 默认会回滚事务.
You don't need to explicitly specify rollbackFor = Throwable.class
, because spring will by default rollback the transaction if an Error
occurs.
在其默认配置中,Spring Framework的事务基础结构代码仅在运行时、未检查异常的情况下将事务标记为回滚;也就是说,当抛出的异常是 RuntimeException 的实例或子类时.(错误也会 - 默认情况下 - 导致回滚).从事务方法抛出的已检查异常不会导致默认配置中的回滚.
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.
或者看看DefaultTransactionAttribute
public boolean rollbackOn(Throwable ex) {
return (ex instanceof RuntimeException || ex instanceof Error);
}
这篇关于Spring 事务:在 Exception 或 Throwable 上回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!