解決 org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class XXX;

最近用spring data jpa操做mongo時進行查詢操做時遇到該錯誤:java

因爲想直接獲取到 實體類的迭代器(如:FindIterable<User> ) 使用了一下方法:spring

template.getCollection(entityInformation.getCollectionName()).find(entityInformation.getJavaType());

  出現如下錯誤:mongodb

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.example.tranfer.entity.User.

	at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
	at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
	at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37)
	at com.mongodb.internal.operation.Operations.createFindOperation(Operations.java:140)

  

解決辦法以下:ide

在本身的repository中注入Mongo轉換器code

@Autowired
    MongoConverter mongoConverter;

  使用方法:orm

while (iterator.hasNext()){
            Document next = iterator.next();
            User user = mongoConverter.read(User.class, next);
            users.add(user);
        }

  MongoTemplate就是這麼作的blog

相關文章
相關標籤/搜索