我们使用具有声明性事务管理的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(实体)后抛出错误;但事务没有标记为回滚,因此最终用户将获得错误页面,但在场景实体后面得到了持久化。
有什么方法可以回滚事务吗?
您可以执行以下操作。
@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()抛出异常时,整个事务将被回滚。