春季交易:rollbackfor和norollbackfor都已定义 [英] Spring Transaction : rollbackfor and norollbackfor both defined

查看:688
本文介绍了春季交易:rollbackfor和norollbackfor都已定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在必须维护的应用程序中遇到的问题:

Here is the problem I got in an application I have to maintain:

我有一个带有注释@Transactional(rollbackFor = CustomExceptionA.class)的头等舱 然后在下面的代码中,我调用@Transactional(noRollbackFor = CustomExceptionB.class)的方法 注意:CustomExceptionACustomExceptionB只有一个共同的祖先是Exception.

I have a first class with the annotation @Transactional(rollbackFor = CustomExceptionA.class) Then in the following code I call a method of @Transactional(noRollbackFor = CustomExceptionB.class) NB : CustomExceptionA or CustomExceptionB have only one common ancestor wich is Exception.

当然,当我执行代码时,引发的异常既不是CustomExceptionACustomExceptionB类型,也不是它们的子类.

And of course, when I execute the code an exception is raised wich is neither of type CustomExceptionA or CustomExceptionB nor does it subclasses them.

所以问题很简单: 在这种情况下,交易会发生什么??它会回滚吗?它是否处于未完成状态,等待应用程序执行某些操作(这实际上是一个答案,可能解释了该应用程序中看到的一些难看的事情)?而且:为什么?

So the question is simple : What happens to the transaction in that case ? Does it commit ? Does it rollback ? Does it hold on an unfinished state waiting for the application to do something (which is actually an answer that might explain some ugly things seen in this application) ? and moreover : why ?

感谢您的帮助和时间.

Thanks for your help and time.

推荐答案

默认情况下,Spring Framework的事务基础结构代码仅在运行时未检查的异常的情况下才将事务标记为回滚.也就是说,当抛出的异常是RuntimeException的实例或子类时. (默认情况下,错误也会导致回滚.)从事务方法抛出的检查异常不会导致事务回滚.

Spring Framework's transaction infrastructure code will, by default, only mark 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 will not result in the transaction being rolled back.

为什么?这完全有道理:检查的异常对于处理或抛出是强制性的,因此,如果将检查的异常从事务方法中抛出,则框架假设您知道自己在做什么.如果发生未阻止的异常,则可能是错误或异常处理漏洞,因此应回滚事务以避免数据损坏.

Why? That makes a perfect sense: checked exceptions are mandatory for handling or throwing out, so if you're throwing the checked exception out of the transactional method, then framework supposes you know what you're doing. In case of unchecled exceptionit's likely to be a bug, or exception handling flaw, so transaction is rolled back to avoid data corruption.

这篇关于春季交易:rollbackfor和norollbackfor都已定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆