简体   繁体   English

@事务回滚For scope

[英]@Transactional rollbackFor scope

I'm using @Transactional in my code and I'm created a custom exception to show error messages in specific format in UI.我在我的代码中使用@Transactional ,并创建了一个自定义异常以在 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:我的问题是:

  1. If I'm mentioning MyCustomException.class in rollbackFor , do I need to also mention RuntimeException.class, Exception.class .如果我在rollbackFor中提到MyCustomException.class ,我是否还需要提到RuntimeException.class, Exception.class Or whatever is mentioned in rollbackFor gets appended along with default exceptions for which transaction is rolled-back.或者rollbackFor中提到的任何内容都会与事务回滚的默认异常一起附加。

  2. Although I'm escaping the MyCustomException from businessMethod() , but I'm catching it on its calling method getMyData() .虽然我是 escaping 来自businessMethod()MyCustomException ,但我在它的调用方法getMyData()上抓住了它。 I'm assuming that the transaction will be rolled-back in case of exception, correct?我假设事务将在出现异常时回滚,对吗?

  1. The transaction will be rolled back on any RuntimeException , so it is not necessary to declare your own MyException.class in rollbackFor section, since your MyException extends RuntimeException .事务将在任何RuntimeException上回滚,因此无需在rollbackFor部分声明您自己的MyException.class ,因为您的MyException扩展了RuntimeException If you declare Exception.class the rollback will be performed on any Exception.如果您声明Exception.class ,则将对任何异常执行回滚。 But in your case you do not need rollbackFor at all.但是在您的情况下,您根本不需要rollbackFor

  2. Yes, it is correct.是的,这是正确的。 Your transcation starts and ends in businessMethod() .您的交易在businessMethod()开始和结束。

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

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