【问题标题】:Spring declarative transaction management and rollback handlingSpring 声明式事务管理和回滚处理
【发布时间】:2016-01-18 09:19:04
【问题描述】:

我们正在使用带有声明式事务管理的 Spring 4.x 和 Spring Data JPA,我有一个控制器、服务和一个存储库,如下面的伪代码。

@Service
@Transactional(readOnly=true)
public class SampleService {

     @Autowired
     private SampleRepository sampleRepository;

     @Transactional
     public MyEntity saveMyEntity(MyEntity entity) {
      //do some business logic
      return sampleRepository.save(entity);
     }
}

public class SampleController {

    @Autowired
    private SampleService sampleService; 

    public String saveSample(@Valid MyEntity entity) {
       //Validation
       //If Valid
       sampleService.saveMyEntity(entity);
       //After saving do some view related rendering logic
       //Assume here view related rendering logic throws Exception
       return "view"  
    }
}

在上面的代码中,调用 sampleService.saveMyEntity(entity); 后会引发错误,但事务没有标记为回滚,因此最终用户会在后台看到错误页面实体被持久化了。

有什么办法可以回滚事务吗?

【问题讨论】:

  • 也许这个可以帮助你:stackoverflow.com/questions/16167278/…
  • @Teo 谢谢但不完全相同的问题,这里我的 sampleService.saveMyEntity 方法返回没有任何异常。在该服务调用之后和我的控制器内部发生了这里异常。
  • 事务在 saveMyEntity() 完成后提交。之后您无法回滚。您需要扩大事务的范围以包含额外的逻辑。
  • @AlanHay 扩大范围我可以有两种方法,一种是像 Shazin 提到的在控制器级别添加事务注释或在过滤器中打开事务。老实说,控制器级别的事务似乎不是一个好习惯,仍然必须涵盖从其他过滤器链抛出的异常范围,一个可能的解决方案是在过滤器中启动事务并手动处理提交和回滚。但我不知道这个问题是否有更好的选择。

标签: spring spring-mvc spring-transactions


【解决方案1】:

您可以执行以下操作。

@Transactional(rollbackFor=Exception.class)
public String saveSample(@Valid MyEntity entity) {
   //Validation
   //If Valid
   sampleService.saveMyEntity(entity);
   //After saving do some view related rendering logic
   //Assume here view related rendering logic throws Exception
   return "view"  
}

由于默认的事务传播是必需的,而不是必需的新的。事务实际上将从SampleController.saveSample() 开始,并且将使用相同的SampleService.saveMyEntity()。当 saveSample() 抛出异常时,整个事务将被回滚。

【讨论】:

  • 如果我将事务范围扩大到控制器,它会起作用,但我认为在控制器级别添加事务不是一个好习惯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 2011-10-18
  • 1970-01-01
  • 2013-02-19
  • 2011-04-12
  • 2011-10-06
  • 1970-01-01
相关资源
最近更新 更多