JavaSpringBatch:即使捕获到异常,为什么事务仍在回滚
我使用的是Spring批处理,我的步骤配置如下:
@Bean
public Step testStep(
JdbcCursorItemReader<TestStep> testStageDataReader,
TestStepProcessor testStepProcessor,
CompositeItemWriter<Writer> testWriter,
PlatformTransactionManager transactionManager,
JobRepository jobRepository) {
return stepBuilderFactory
.get("TESTING")
.<>chunk(100)
.reader(testStageDataReader)
.processor(testStepProcessor)
.writer(testWriter)
.transactionManager(transactionManager)
.repository(jobRepository)
.build();
}
在我的作者中:
void write(List<? extends TestEntity> items) {
try {
testRepository.saveAll(items);
} catch (Exception exp) {
log.error("Exception while writing the batch", Exp);
//If there is an exception try individual items and skip filed ones
items.forEach(eachTask -> {
try {
testRepository.save(eachTask);
} catch (Exception exp) {
logException(exp, eachTask.getId());
}
});
}
对于代码,我希望如果批处理出现问题,那么我将尝试单个项目并跳过失败的项目
然而,这并没有发生。事务似乎已丢失且未恢复
# 1 楼答案
这种期望是不正确的。当从项目编写器引发可跳过的异常时,将触发区块扫描。从您的配置来看,情况似乎并非如此:您没有配置任何可跳过的异常,并且您的编写器也没有抛出异常。步骤定义应类似于:
你的作者应该在某个时候抛出
MySkippableException