在Spring batch 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");
}
}
发布于 2020-07-28 20:10:18
具有@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)
,但您必须认真考虑是否需要额外的事务。
https://stackoverflow.com/questions/63111794
复制相似问题