2016-01-18 44 views
0

我们使用Spring 4.x和Spring Data JPA进行声明式事务管理,我有一个Controller,Service和一个类似下面伪代码的仓库。春季声明式事务管理和回滚处理

@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(实体);但事务并不标记为回滚,所以最终用户将得到一个错误页面,但在场景实体后面持续。

有什么办法可以回滚交易吗?

+0

也许这一个可以帮助你:http://stackoverflow.com/questions/16167278/spring-transaction-doesnt-rollback – Teo

+0

@Teo谢谢但不完全相同的问题,在这里我的sampleService.saveMyEntity方法返回没有任何异常。这个服务调用之后和我的控制器内部发生异常。 – Nick

+1

saveMyEntity()完成后提交事务。之后你不能回滚。您需要扩大事务的范围以包含额外的逻辑。 –

回答

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()抛出异常时,整个事务将被回滚。

+0

它的真实如果我扩大事务范围控制器它将工作,但我认为它不是一个好的做法,以添加交易控制器级别。 – Nick