捕获异常,更改实体,提交并重新抛出异常

时间:2018-10-22 12:11:55

标签: hibernate spring-boot spring-data-jpa

我有以下情况:

MyStoredEntity myStoredEntity = myStoredEntityService.get(id)
try {   
    myStoredEntityService.doSomething()
} catch (GeneralException) {
    myStoredEntity.setFail(true)
    throw e;
}

所有这些代码都在@Transactional(propagation = Propagation.REQUIRES_NEW)中。基本上,我想调用doSomething,如果抛出异常,则设置实体的字段,提交并重新抛出异常。但是,它不起作用,因为该事务被标记为回滚。

1 个答案:

答案 0 :(得分:1)

您可以将noRollbackFor批注的@Transactional参数用于运行时异常,而这些异常要在没有事务回滚的情况下捕获。像这样:

@Transactional(noRollbackFor = {SomeServiceRuntimeException.class})
public foo() {
    MyStoredEntity myStoredEntity = myStoredEntityService.get(id);
    try {   
        myStoredEntityService.doSomething();
    } catch (SomeServiceRuntimeException e) {
        myStoredEntity.setFail(true);
        myStoredEntityService.save(myStoredEntity);
        throw e;
    }
}