通常情况下,向mongodb插入的document中的每一个value只能是基本类型(字符串、数字、时间等),不支持自定义Pojo类型;
例如,直接用mongoTemplate报错下面这个document会报错:can't find a codec for CodecCacheKey...
new Document().append("obj", eachC.getDataValueVo())
解决办法:
采用如下mongoTemplate.getDb().withCodecRegistry方式,可以将自定义Pojo正确持久化到mongodb。
- 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
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);