MongoDB Java 插入引发 org.bson.codecs.configuration.CodecConfigurationException:找不到 io.github.ilkgunel.mongodb.Pojo 类的编解码器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39433775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:08:54  来源:igfitidea点击:

MongoDB Java Inserting Throws org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class io.github.ilkgunel.mongodb.Pojo

javamongodb

提问by ?lkay Gunel

I'm learning MongoDB with Java. I'm trying to insert data to MongoDB with Java driver. I'm doing inserting like in MongoDB tutorial and every thing is okey. But if I want to insert a variable and when I run the code, driver throws an error like this:

我正在用 Java 学习 MongoDB。我正在尝试使用 Java 驱动程序将数据插入到 MongoDB。我正在做 MongoDB 教程中的插入操作,一切都很好。但是如果我想插入一个变量并且当我运行代码时,驱动程序会抛出这样的错误:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class io.github.ilkgunel.mongodb.Pojo.

I searhed questions in Stack Overflow like this but I couldn't understand anything and I cant't find anything to solve this error. My code is below. How can solve this problem?

我像这样在 Stack Overflow 中搜索了问题,但我什么也不懂,也找不到任何解决此错误的方法。我的代码如下。如何解决这个问题?

I'm using this code:

我正在使用此代码:

package io.github.ilkgunel.mongodb;
import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

public class MongoDBBasicUsage {
    public static void main(String[] args) {
        MongoClient mongoClient;
        try {
            Pojo pojo = new Pojo();
            mongoClient = new MongoClient("localhost", 27017);
            MongoDatabase database = mongoClient.getDatabase("MongoDB");

            pojo.setId("1");
            pojo.setName("ilkay");
            pojo.setSurname("günel");

            Document document = new Document();
            document.put("person", pojo);

            database.getCollection("Records").insertOne(document);  
        } catch (Exception e) {
            System.err.println("Bir Hata Meydana Geldi!");
            System.out.println("Hata" + e);
        }
    }
}

My Pojo is this:

我的 Pojo 是这样的:

    package io.github.ilkgunel.mongodb;

public class Pojo {
    String name;
    String surname;
    String id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    } 
}

回答by Dallas Phillips

From the looks of what you are trying to do, you are trying to add some custom data type (in this case your POJO) but what you need to keep in mind is that fields in documents can only accept certain data types, not objects directly.

从您尝试执行的操作来看,您正在尝试添加一些自定义数据类型(在本例中为您的 POJO),但您需要记住的是,文档中的字段只能接受某些数据类型,而不能直接接受对象.

In case if you didn't know also, Mongo Documents are structured the same way as json. So you have to explicitaly create the documents by creating the fields and inserting the values into them. There are specific data types that are allowed in value fields:

如果您也不知道,Mongo 文档的结构与 json 相同。因此,您必须通过创建字段并将值插入其中来显式地创建文档。值字段中允许使用特定的数据类型:

http://mongodb.github.io/mongo-java-driver/3.0/bson/documents/

http://mongodb.github.io/mongo-java-driver/3.0/bson/documents/

To help with your case, the code below takes your POJO as a parameter and knowing the structure of the POJO, returns a Mongo Document that can be inserted into your collection:

为了帮助您解决问题,下面的代码将您的 POJO 作为参数并了解 POJO 的结构,返回一个可以插入到您的集合中的 Mongo 文档:

private Document pojoToDoc(Pojo pojo){
    Document doc = new Document();

    doc.put("Name",pojo.getName());
    doc.put("Surname",pojo.getSurname());
    doc.put("id",pojo.getId());

    return doc;
} 

This should work for insertion. If you want to index one of the fields:

这应该适用于插入。如果要索引其中一个字段:

database.getCollection("Records").createIndex(new Document("id", 1));

I hope this answers your question and works for you.

我希望这能回答您的问题并对您有用。

回答by hankchan101

did you check the library of mongodb. I solve this problem in this morning by change the mongodb java driver from 3.2.2 to 3.4.2. the new maven like that:

你检查了mongodb的图书馆。我今天早上通过将 mongodb java 驱动程序从 3.2.2 更改为 3.4.2 解决了这个问题。像这样的新专家:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
    <version>1.5.4.RELEASE</version>
</dependency>

have a try and response

有一个尝试和回应

回答by Renato Oliveira

You need to configure the CodeRegistry to use the PojoCodecProvider as explained here: http://mongodb.github.io/mongo-java-driver/3.7/driver/getting-started/quick-start-pojo/

您需要配置 CodeRegistry 以使用 PojoCodecProvider,如下所述:http://mongodb.github.io/mongo-java-driver/3.7/driver/getting-started/quick-start-pojo/

回答by Hasnaa Ibraheem

To be bit abstract, as this may save the day for other developers..
This error: CodecConfigurationException: Can't find a codec for class xxxmeans that your mongo driver is not able to handle the data you sent in the object you made of that xxx class and accordingly can't generate the mongo query you want.

The resolution in that case would be either to use the right class i.e to use one of the expected classes by the driver (in my case replacing java array by ArrayList object resolved the issue).. The other resolution could be to upgrade your driver. Third solution could be as mentioned by @Renato, to define your own decoding logic.. This depends on your exact case.
hth

有点抽象,因为这可能会为其他开发人员节省一天..
此错误:CodecConfigurationException: 找不到类 xxx 的编解码器意味着您的 mongo 驱动程序无法处理您在您制作的对象中发送的数据该 xxx 类因此无法生成您想要的 mongo 查询。

在这种情况下,解决方案要么是使用正确的类,即使用驱动程序预期的类之一(在我的情况下,用 ArrayList 对象替换 java 数组解决了该问题)。另一个解决方案可能是升级您的驱动程序。第三个解决方案可能是@Renato 提到的,定义您自己的解码逻辑。这取决于您的具体情况。

回答by Hendy Irawan

I'm using MongoDB POJO support. In my case, I had this "clue" WARNing before the exception:

我正在使用MongoDB POJO 支持。就我而言,在异常之前我有这个“线索”警告:

 org.bson.codecs.pojo                     : Cannot use 'UserBeta' with the PojoCodec.

org.bson.codecs.configuration.CodecConfigurationException: Property 'premium' in UserBeta, has differing data types: TypeData{type=PremiumStatus} and TypeData{type=Boolean}.

My class UserBetahad getPremium(), setPremium(), and isPremium(). I already @BsonIgnore-d the isPremium()but for some reason it's still detected and causing conflict.

我班UserBetagetPremium()setPremium()isPremium()。我已经@BsonIgnore-disPremium()但出于某种原因它仍然被检测到并导致冲突。

My workaround is to rename isPremium()to isAnyPremium().

我的解决方法是重命名isPremium()isAnyPremium().

回答by Rami DH

I resolve it by adding the spring-boot-starter-data-mongodb dependency in your pom.xml or your build.gradle.

我通过在 pom.xml 或 build.gradle 中添加 spring-boot-starter-data-mongodb 依赖项来解决它。

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb', version: '2.2.4.RELEASE'

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb', version: '2.2.4.RELEASE'

回答by Mukundhan

Documentation: MongoDB Driver Quick Start - POJOs

文档: MongoDB 驱动程序快速入门 - POJO

After following the above document, if you are still getting error, then

按照上述文档操作后,如果仍然出现错误,则

you could be using a generic documentinside your collectionlike

您可以在您的收藏中使用通用文档,例如

class DocStore {
  String docId:
  String docType;
  Object document; // this will cause the BSON cast to throw a codec error
  Map<String, Object> document; // this won't
}

And still, you would want to cast your document from POJOto Map

而且,您仍然希望将文档从POJO 转换Map

mkyongtutorial could help.

mkyong教程可以提供帮助。

As for the fetch, it works as expected but you might want to cast from Map to your POJO as a post-processing step, we can find some good answers here

至于获取,它按预期工作,但您可能希望从 Map 转换到您的 POJO 作为后处理步骤,我们可以在这里找到一些好的答案

Hope it helps! ?

希望能帮助到你!?

回答by Lakshmi Narayanan

Use below set of lines while making connection to mongo db for resolving the issue with codec, while using POJO class in mongo.

在连接到 mongo db 以解决编解码器问题时使用下面的行集,同时在 mongo 中使用 POJO 类。

Reference : https://developer.mongodb.com/quickstart/java-mapping-pojos

参考:https: //developer.mongodb.com/quickstart/java-mapping-pojos

ConnectionString connectionString = new ConnectionString("mongodb://" + username + ":" + password + "@" + host + ":" + port);
CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);

MongoClientSettings clientSettings = MongoClientSettings.builder()
                .applyConnectionString(connectionString)
                .codecRegistry(codecRegistry)
                .build();
MongoClient mongoClient = MongoClients.create(clientSettings);
MongoDatabase mongoDatabase = mongoClient.getDatabase(database);