如何在 Spring 批处理中使用 MongoItemWriter 更新和插入文档?
How to update and insert a document using MongoItemWriter in Spring Batch?
在涉及读写MongoDB的Spring批处理项目中,使用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文档的class的对象,以便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-核心 5.1.3.RELEASE
- spring-批次 4.1.0.RELEASE
- spring-数据-mongodb 2.1.3.RELEASE
现在,这会将 newSampleItem
保存到 XYZCollection
中,因为它必须这样做。要求是使 Spring-批量更新已读取的 sampleItem
,然后为 newSampleItem
对象创建一个新文档。有可能这样做吗?如果是,如何?
您可以将 CompositeItemWriter
与两个编写器一起使用,一个更新项目,另一个插入新文档:
- 对于插入,您可以使用已有的编写器。
- 对于更新,您需要创建一个新的编写器来扩展
MongoItemWriter
并覆盖 doWrite
以更新项目。这是因为 MongoItemWriter
允许删除或保存文档,但不能更新文档。
然后使用两位作者作为 CompositeItemWriter
的代表。
在涉及读写MongoDB的Spring批处理项目中,使用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文档的class的对象,以便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-核心 5.1.3.RELEASE - spring-批次 4.1.0.RELEASE - spring-数据-mongodb 2.1.3.RELEASE
现在,这会将 newSampleItem
保存到 XYZCollection
中,因为它必须这样做。要求是使 Spring-批量更新已读取的 sampleItem
,然后为 newSampleItem
对象创建一个新文档。有可能这样做吗?如果是,如何?
您可以将 CompositeItemWriter
与两个编写器一起使用,一个更新项目,另一个插入新文档:
- 对于插入,您可以使用已有的编写器。
- 对于更新,您需要创建一个新的编写器来扩展
MongoItemWriter
并覆盖doWrite
以更新项目。这是因为MongoItemWriter
允许删除或保存文档,但不能更新文档。
然后使用两位作者作为 CompositeItemWriter
的代表。