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


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

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

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

  出現以下錯誤:

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)

  

解決辦法如下:

在自己的repository中注入Mongo轉換器

  @Autowired
    MongoConverter mongoConverter;

  使用方法:

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

  MongoTemplate就是這么做的

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM