解决 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