Reputation: 782
In a Spring Batch project involving reading and writing to MongoDB, writing to MongoDB using MongoItemWriter
is configured like this:
<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>
The writer bean is configured like this:
<bean id="writer"
class="org.springframework.batch.item.data.MongoItemWriter">
<property name="template" ref="mongoTemplate" />
<property name="collection"
value="XYZCollection" />
</bean>
Then we have the model:
public class Sample {
@Id
private ObjectId id;
@Field(“Field1”)
private String field1;
@PersistenceConstructor
public Sample() { }
// getter and setters
}
Finally, from the processor
, the object of the class whose model makes up the MongoDB document is returned, so that the ItemWriter
will pick it up for inserting into the database:
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;
}
}
Versions used: - spring-core 5.1.3.RELEASE - spring-batch 4.1.0.RELEASE - spring-data-mongodb 2.1.3.RELEASE
Now, this saves the newSampleItem
into XYZCollection
as it has to. The requirement is to make Spring-Batch update the sampleItem
that got read and then create a new document for the newSampleItem
object. Is it possible to do so? If yes, how?
Upvotes: 4
Views: 3815
Reputation: 31600
You can use a CompositeItemWriter
with two writers, one that updates the item and another one that inserts the new document:
MongoItemWriter
and override doWrite
to update the item. This is because the MongoItemWriter
allows to either remove or save a document, but not update a document.Then use both writers as delegates to the CompositeItemWriter
.
Upvotes: 2