Question

I am trying to write a Spring Batch job that reads documents from a mongo db and writes the documents to a CMS (for now I will attempt to test this first with WireMock). Can I set up the job and itemreader without specifying the exact structure of the document? I would just like to read each document as json and then sent that json through to the CMS. Is this even possible?

Was it helpful?

Solution

Since JSON is just a String, you should configure your MongoItemReader for String type and provide MongoTemplate with some custom simple converter:

public class DBObjectToStringConverter implements Converter<DBObject, String> {
  public String convert(DBObject source) {
    return source == null ? null : source.toString();
  }
}

This one just return a String JSON representation of DBObject.

Then configuration:

<mongo:db-factory/>

<mongo:mapping-converter id="mappingConverter">
    <mongo:custom-converters>
        <mongo:converter>
            <bean class="com.my.batch.mongo.DBObjectToStringConverter "/>
        </mongo:converter>
    </mongo:custom-converters>
</mongo:mapping-converter>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory"/>
    <constructor-arg ref="mappingConverter"/>
</bean>

<bean class="org.springframework.batch.item.data.MongoItemReader">
    <property name="template" ref="mongoTemplate"/>
    <property name="query" value="..."/>
    <property name="targetType" value="java.lang.String"/>
</bean>

And voila! Each item returns as JSON String.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top