首页 文章

如何在Spring Batch中使用MongoItemWriter更新和插入文档?

提问于
浏览
0

在涉及读写 MongoDBSpring Batch 项目中,使用 MongoItemWriter 写入 MongoDB 的配置如下:

<batch:job id=“someJob”>
    <batch:step id="step1">
        <batch:tasklet>
            <batch:chunk reader=“reader”
                writer=“writer”
                processor=“processor” commit-interval="10" />
        </batch:tasklet>
    </batch:step>
</batch:job>

我们配置writer bean:

<bean id="writer"
    class="org.springframework.batch.item.data.MongoItemWriter">
    <property name="template" ref="mongoTemplate" />
    <property name="collection"
        value="XYZCollection" />
</bean>

然后我们有模型:

public class Sample {

    @Id
    private ObjectId id;

    @Field(“Field1”)
    private String field1;

    @PersistenceConstructor
    public Sample() { }

    // getter and setters

}

最后,从 processor 返回其模型构成 MongoDB 文档的类的对象,以便 ItemWriter 将其选中以插入数据库:

public class Processor implements ItemProcessor<Sample, Sample> {

    @Override
    public Sample process(Sample sampleItem) throws Exception {
        Sample updatedSampleItem = updateSampleItem(sampleItem);
        Sample newSampleItem = createSampleItem(sampleItem);
        return newSampleItem;
    }
}

正在使用 spring-core 5.1.3.RELEASEspring-batch 4.1.0.RELEASEspring-data-mongodb 2.1.3.RELEASE 版本 .

现在,这将 newSampleItem 保存到 XYZCollection 中 . 要求是使 Spring-Batch 更新已读取的 sampleItem ,然后为 newSampleItem 对象创建新文档 . 有可能这样做吗?如果有,怎么样?

1 回答

  • 1

    您可以将 CompositeItemWriter 与两个编写器一起使用,一个用于更新项目,另一个用于插入新文档:

    • 对于插入,您可以使用已有的编写器 .

    • 对于更新,您需要创建一个扩展 MongoItemWriter 的新编写器并覆盖 doWrite 以更新该项目 . 这是因为 MongoItemWriter 允许删除或保存文档,但不允许更新文档 .

    然后使用两个编写器作为 CompositeItemWriter 的代理 .

相关问题