【问题标题】:Spring Boot - how to call another method outside of the transaction scopeSpring Boot - 如何在事务范围之外调用另一个方法
【发布时间】:2021-04-19 14:12:54
【问题描述】:

我有以下方法:

    @Transactional
    public Store handle(Command command) {
        Store store= mapper.map(command.getStoreDto(), Store.class);
        Store persistedStore = storeService.save(store);
        addressService.saveStoreAddress(store, command.getEmployeeId()); //this method is not crucial, should be called independently and in another transaction, without any rollback in case of exception
        return persistedStore;
    }

addressService.saveStoreAddress 并不重要——当这个方法抛出任何异常时,无论如何都应该保存 store (storeService.save(store);)。就我而言,最好的解决方案是什么?

【问题讨论】:

    标签: spring-boot hibernate spring-transactions


    【解决方案1】:

    saveStoreAddress() 上使用@Transactional(propagation=REQUIRES_NEW),这样它将在新的单独事务中执行。

    为了防止handle()的事务因为saveStoreAddress()的异常抛出而回滚,调用saveStoreAddress()的时候也要try-catch。

    最后,它看起来像:

    @Service
    public class AddressService {
    
       @Transactional(propagation=REQUIRES_NEW)
       public void saveStoreAdress(.....){
    
       }
      
    }
    
    @Transactional
    public Store handle(Command command) {
            .......
            try{
              addressService.saveStoreAddress(store, command.getEmployeeId());
            }catch (Exception ex){
               /***
                * handle the exception thrown from saveStoreAddress.
                * If you want the current transaction not rollback just because of the 
                * exception throw from saveStoreAddress(), do not re-throw the exception when 
                * handling this exception 
                */
            }
            return ....;
    }
    

    【讨论】:

    • 经过一些研究 - 你确定在 saveStoreAdress 异常后(AddressService 调用另一个 web 服务)主事务不会回滚吗?
    • 我想我会收到:UnexpectedRollbackException: 事务静默回滚,因为它已被标记为仅回滚
    • 您必须在saveStoreAdress() 上使用Transactional(propagation=REQUIRES_NEW)。还要确保您不是在 saveStoreAdress() 上“自我调用”,这样 REQUIRES_NEW 将生效并为其启动新的 TX
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2019-12-05
    • 2012-12-24
    • 2020-02-23
    • 2020-08-23
    相关资源
    最近更新 更多