spring-boot - 由于异常回滚后的Spring批量更新数据库状态
问题描述
在 Spring 批处理 Writer 中,我将数据库行状态从 0 更新为 1。如果发生任何异常,则更新为 2。但是由于 @transaction 回滚,我无法将状态更新为 2。
(我抛出异常来触发回滚)
@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");
}
}
解决方案
具有 的方法@Transactional
会在抛出异常时回滚事务。因此,如果异常是您的代码的预期且正常的流程,则不应抛出异常并返回某种结果对象或状态代码。
@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)
但你必须认真考虑是否需要额外的交易。
推荐阅读
- node.js - 如何在 React 中制作临时/一次性使用链接
- c++ - 如何根据采样率和单极低通滤波器 alpha 系数计算截止频率?
- r - R:情绪分析包
- docker - 如何在 docker 卷中复制源代码构建
- sql - 多年来,在 column1 中查找与 column2 中的“DATE”匹配的所有项目
- alignment - 是否有使用点云的基于 slam 的对齐方式?
- ios - 如何过滤 Core Data Song/Playlist 类型关系中的已订购项目?
- reactjs - React JS如何将道具从一个组件传递到另一个组件
- git - GIT - 进行更改后合并问题
- javascript - 是否可以在 Nodejs 中设置参数之前调用函数?