最近用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就是這么做的