英文:
@Transactional rollbackFor scope
问题
我在代码中使用了@Transactional
,并创建了一个自定义异常,以便以特定格式在用户界面显示错误消息。
public class MyCustomException extends RuntimeException
当遇到此异常时,我仍希望像其他任何异常发生的情况一样回滚我的事务。
因此,为了使其工作,我编写了以下代码:
// 从 REST 控制器调用的服务方法
public List<String> getMyData() {
List<String> errors = new ArrayList();
try {
businessMethod();
} catch (MyCustomException e) {
log.error(e.getMessage);
errors.add(e.getMessage)
}
return errors.
}
@Transactional(rollbackFor = {MyCustomException.class, RuntimeException.class, Exception.class})
public String businessMethod() {
// 获取可能抛出 MyCustomException 的数据的业务逻辑
}
我的问题是:
-
如果我在
rollbackFor
中提及了MyCustomException.class
,是否还需要提及RuntimeException.class, Exception.class
?或者在rollbackFor
中提到的内容会与默认的异常一起追加,以进行事务回滚。 -
尽管我从
businessMethod()
中逃逸了MyCustomException
,但我在其调用方法getMyData()
中捕获了它。我假设在发生异常的情况下事务会回滚,正确吗?
英文:
I'm using @Transactional
in my code and I'm created a custom exception to show error messages in specific format in UI.
public class MyCustomException extends RuntimeException
When this exception is encountered I still want to rollback my transactions, same as in case when any other exception occurs.
So to make it work, I writing below code:
// service method called from rest controller
public List<String> getMyData() {
List<String> errors = new ArrayList();
try {
businessMethod();
} catch (MyCustomException e) {
log.error(e.getMessage);
errors.add(e.getMessage)
}
return errors.
}
@Transactional(rollbackFor = {MyCustomException.class, RuntimeException.class, Exception.class})
public String businessMethod() {
// Business logic to get data that can throw MyCustomException
}
My questions are:
-
If I'm mentioning
MyCustomException.class
inrollbackFor
, do I need to also mentionRuntimeException.class, Exception.class
. Or whatever is mentioned inrollbackFor
gets appended along with default exceptions for which transaction is rolled-back. -
Although I'm escaping the
MyCustomException
frombusinessMethod()
, but I'm catching it on its calling methodgetMyData()
. I'm assuming that the transaction will be rolled-back in case of exception, correct?
答案1
得分: 1
-
在任何“RuntimeException”情况下,事务将被回滚,因此在“rollbackFor”部分中声明您自己的“MyException.class”是不必要的,因为您的“MyException”扩展了“RuntimeException”。如果您声明“Exception.class”,则将在任何异常情况下执行回滚。但在您的情况下,您根本不需要“rollbackFor”。
-
是的,这是正确的。您的事务在“businessMethod()”中启动并结束。
英文:
-
The transaction will be rolled back on any
RuntimeException
, so it is not necessary to declare your ownMyException.class
inrollbackFor
section, since yourMyException
extendsRuntimeException
. If you declareException.class
the rollback will be performed on any Exception. But in your case you do not needrollbackFor
at all. -
Yes, it is correct. Your transcation starts and ends in
businessMethod()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论