我正在编写一个 Spring Batch 流程来将数据集从一个系统迁移到另一个系统。在这种情况下,这就像使用RowMapper
实现在传递给查询之前从查询构建对象ItemWriter
. The ItemWriter
称为save
我的 DAO 上的方法(定义为接口并由 spring 数据处理)
问题是这样的:我对 MyItem 表有唯一的约束,因此保存重复的记录将导致DataIntegrityViolationException
。我尝试过在ItemWriter
允许我记录未导入的记录,但是在执行过程中它永远不会进入此 catch 语句。我尝试过捕捉Exception
AND Throwable
也无济于事。
据我观察,有一个@Transactional
我的 DAO 的“保存”方法上的注释,我希望在其中发生提交和刷新。 Spring Batch 是否会以任何方式改变此事务?这样使得@Transactional
注释适用于 'write' 方法ItemWriter
?
我什至可以捕获这个类中的异常吗?
我在下面提供了代码片段,如果您需要更多信息 - 请告诉我。
非常感谢您提供的任何帮助
项目编写器
@Component
public class MyItemWriter implements ItemWriter<MyItem> {
private static final Logger LOG = LoggerFactory.getLogger(MyItemWriter.class);
@Resource
private MyItemDao myItemDao;
@Override
public void write(List<? extends MyItem> myItems) throws Exception {
for (MyItem myItem : myItems) {
try {
myItemDao.save(myItem);
} catch (Throwable ex) {
LOG.warn("Failed to import MyItem: {}: {} ", myItem.getId(), ex.toString());
}
}
}
}
DAO
public interface MyItemDao extends PagingAndSortingRepository<MyItem, Integer> {
[Custom methods omitted]
}
Spring批量配置
<batch:job id="myImportJob" restartable="true" job-repository="jobRepository">
<batch:step id="myImportStep" allow-start-if-complete="true">
<batch:tasklet>
<batch:chunk reader="myItemReader" writer="myItemWriter" commit-interval="50" />
</batch:tasklet>
</batch:step>
</batch:job>