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

时间:2018-12-09 18:17:05

标签: java spring mongodb spring-batch spring-data-mongodb

在涉及读写MongoDB的Spring 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;
    }
}

使用的版本: -弹簧芯5.1.3发布 -春季批量4.1.0.RELEASE -spring-data-mongodb 2.1.3.RELEASE

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

1 个答案:

答案 0 :(得分:1)

您可以将CompositeItemWriter与两名作家一起使用,一名作家更新项目,另一名作家插入新文档:

  • 对于插入,您可以使用已有的作家。
  • 要进行更新,您需要创建一个扩展MongoItemWriter并覆盖doWrite的新编写器以更新该项目。这是因为MongoItemWriter允许删除或保存文档,但不允许更新文档。

然后同时使用两个编写者作为CompositeItemWriter的代表。