在Spring Batch Writer中,我将数据库行状态从0更新为1。如果发生任何异常,请更新为2。 但是由于@transaction rollback,我无法将状态更新为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");
}
}
答案 0 :(得分:0)
具有sudo apt install r-cran-rpostgres
的方法在引发异常时将回滚事务。因此,如果异常是代码的预期且正常运行,则不应抛出异常并返回某种结果对象或状态代码。
@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
}
[...]
}
,但您必须认真考虑是否需要进行额外的交易。