简体   繁体   中英

Spring batch Item Reader with Mongodb source : How to convert DBObject to a custom POJO in the ItemReader?

I use spring batch with mongodb as datasource and I would like my ItemReader return type to be something else than a DBObject.

I made a converter :

public class CourseDataConverter implements Converter<DBObject, CourseData> {...

but I dont see where I can put this converter in the configuration (I use Java config)

public class BatchConfiguration {
@Autowired
MongoTemplate mongoTemplate;

@Autowired
SessionFactory sessionFactory;

@Bean
@StepScope
public ItemReader<DBObject> reader() {
    MongoItemReader<DBObject> mongoItemReader = new MongoItemReader<DBObject>();
    mongoItemReader.setTemplate(mongoTemplate);
    mongoItemReader.setCollection("pmu");
    mongoItemReader.setQuery("{}");
    mongoItemReader.setTargetType(DBObject.class);
    Map<String, Sort.Direction> sort = new HashMap<String, Sort.Direction>();
    sort.put("_id", Sort.Direction.ASC);
    mongoItemReader.setSort(sort);

    return mongoItemReader;
}

As mentioned in the documentation , unless explicitly configured, Spring-Data-MongoDB creates an instance of MappingMongoConverter by default when you create a MongoTemplate . You can create your own instance of the MappingMongoConverter . By creating your own instance, you can register Spring converters to map specific classes to and from the database. Would suggest a read on the documentation corresponding to the version of Spring-Data-MongoDB you are using, as there is lucid explanation with example(s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM