通常情况下,向mongodb插入的document中的每一个value只能是基本类型(字符串、数字、时间等),不支持自定义Pojo类型;
例如,直接用mongoTemplate报错下面这个document会报错:can't find a codec for CodecCacheKey...
new Document().append("obj", eachC.getDataValueVo())
解决办法:文章来源:https://www.toymoban.com/news/detail-701566.html
采用如下mongoTemplate.getDb().withCodecRegistry方式,可以将自定义Pojo正确持久化到mongodb。文章来源地址https://www.toymoban.com/news/detail-701566.html
Document valueDoc = new Document().append("obj", eachC.getDataValueVo()).append("txt", eachC.getTextValue());
dataDoc.append(eachF.calcDataDocKey(), valueDoc);
//准备要插入数据库的Document集合 rowDataDocList
//获取到已经注册了CodecRegistry的MongoCollection,然后进行批量插入操作。
CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();
CodecRegistry fromProvider = CodecRegistries.fromProviders( new CodecProvider[] {PojoCodecProvider.builder().automatic(true).build()});
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(new CodecRegistry[]{defaultCodecRegistry, fromProvider});
MongoCollection<Document> collection =
mongoTemplate.getDb().withCodecRegistry(pojoCodecRegistry).getCollection(tableName);
List<? extends WriteModel<? extends Document>> writeModelList = (List)rowDataDocList.stream().map((each) -> { return new InsertOneModel(each); }).collect(Collectors.toList());
BulkWriteResult bulkWriteResult = collection.bulkWrite(writeModelList);
到了这里,关于Save POJO to MongoDB的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!