首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring批量更新数据库异常回档后的状态

Spring批量更新数据库异常回档后的状态
EN

Stack Overflow用户
提问于 2020-07-27 16:49:51
回答 1查看 122关注 0票数 0

在Spring batch Writer中,我正在将数据库行的状态从0更新为1。如果发生任何异常,请更新为2。但是,由于@transaction回滚,我无法将状态更新为2。

(我抛出异常来触发回滚)

代码语言:javascript
运行
复制
@Override
@Transactional
public void write(List<? extends TestEntity> enityList) throws Exception {
    
    for(TestEntity testEntity : enityList) {
        try {
            
        
            testEntity.setStatus(2);
            testRepository.save(testEntity);
            testRepository.flush();
            
            testMethod(testEntity); (which throws exception)
        
        }catch (Exception exception) {              
            testEntity.setStatus(2);
            testRepository.save(testEntity);
        }
        
    }
}   



@Transactional
public void testMethod(TestEntity testEntity) throws Exception {

    try{

    //Some service call
    //...
    
    } catch(Exception e) {
            log.error("error", e);
            throw new Exception("exp");
    }

}
EN

回答 1

Stack Overflow用户

发布于 2020-07-28 20:10:18

具有@Transactional的方法在抛出异常时将回滚事务。因此,如果异常是预期的、正常的代码流,则不应该抛出异常并返回某种类型的结果对象或状态代码。

代码语言:javascript
运行
复制
@Transactional
public void testMethodThatIsAllowedToFail(TestEntity testEntity) {
    try{
        //Some service call
    } catch(Exception e) {
        return Status.FAILURE; // enum you have to create
    }
    return Status.SUCCESS;
}

// spring batch writer
public void write(List<? extends TestEntity> enityList) throws Exception {
    [...]
    Status result = testMethod(testEntity); (which throws exception);
    if (result != Status.SUCCESS) {
        // do something with it
    }
    [...]
}

您也可以尝试使用@Transactional(propagation = Propagation.REQUIRES_NEW),但您必须认真考虑是否需要额外的事务。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63111794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档