我使用 Spring Batch 和 mongodb 作为数据源,我希望我的 ItemReader 返回类型不是 DBObject。
我做了一个转换器:
public class CourseDataConverter implements Converter<DBObject, CourseData> {...
但我不知道可以将此转换器放在配置中的何处(我使用 Java 配置)
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;
}
最佳答案
如 documentation 中所述,除非显式配置,否则 Spring-Data-MongoDB 在创建 MongoTemplate
时默认创建一个 MappingMongoConverter
实例。
您可以创建自己的 MappingMongoConverter
实例。通过创建您自己的实例,您可以注册 Spring 转换器以将特定类映射到数据库或从数据库映射特定类。建议阅读与您正在使用的 Spring-Data-MongoDB 版本相对应的文档,因为其中有清晰的示例解释。
关于java - 带有 Mongodb 源的 Spring 批处理项目读取器 : How to convert DBObject to a custom POJO in the ItemReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31369344/