【问题标题】:Catch an exception, change an entity, commit, and rethrow the exception捕获异常、更改实体、提交并重新抛出异常
【发布时间】:2018-10-22 12:11:55
【问题描述】:

我有以下情况:

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

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

【问题讨论】:

  • 你能发布你的整个代码吗?我想看看你在哪里调用这个方法。

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


【解决方案1】:

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

@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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 2011-06-27
    • 2010-10-03
    • 2013-10-04
    • 2020-02-13
    • 1970-01-01
    • 2013-06-24
    • 2016-02-17
    相关资源
    最近更新 更多