简体   繁体   English

无法在 MongoDB 中创建实体

[英]Can´t create entity in MongoDB

I am brand new to MongoDB, so sorry if the question is basic.我是 MongoDB 的新手,如果问题是基本的,那么抱歉。

I am trying to get a basic CRUD working with Java basic objects (POJOs), but this code fails.我正在尝试使用 Java 基本对象 (POJO) 获得基本 CRUD,但此代码失败。 (What is the correct way of doing this? I think it might be close to this): (这样做的正确方法是什么?我认为它可能接近于此):

BasicDBObject document = new BasicDBObject();
document.put("name", user);
dbCollection.insert(document);

This is the message I am getting:这是我收到的消息:

Exception in thread "main" java.lang.IllegalArgumentException: can't serialize class entities.users.NormalUser
    at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:270)
    at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:174)
    at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:120)
    at com.mongodb.DefaultDBEncoder.writeObject(DefaultDBEncoder.java:27)
    at com.mongodb.OutMessage.putObject(OutMessage.java:289)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:261)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
    at com.mongodb.DBCollection.insert(DBCollection.java:75)
    at com.mongodb.DBCollection.insert(DBCollection.java:59)
    at com.mongodb.DBCollection.insert(DBCollection.java:104)
    at repositories.UsersRepository.createUser(UsersRepository.java:53)
    at repositories.UsersRepository.main(UsersRepository.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

You cannot simply serialize every class you have in your application with the mongo java driver.您不能简单地使用 mongo java 驱动程序序列化应用程序中的每个类。 Either, you stick to JSON documents and their supported data types (basically string, various numbers, boolean, date) or you actually write a custom codec for your class, so that the internal Bson conversion can work with it.要么坚持使用 JSON 文档及其支持的数据类型(基本上是字符串、各种数字、布尔值、日期),要么实际为类编写自定义编解码器,以便内部 Bson 转换可以使用它。

Only link I found to a basic example unfortunately in German: https://dev-tek.de/lexicon/Entry/64-MongoDB-Anleitung-Custom-codecs-mit-Hilfe-des-DocumentCodecs/ - but maybe the code helps to understand.不幸的是,我在德语中找到了一个基本示例的链接: https : //dev-tek.de/lexicon/Entry/64-MongoDB-Anleitung-Custom-codecs-mit-Hilfe-des-DocumentCodecs/ - 但也许代码有帮助了解。

Addendum, regarding the comment:附录,关于评论:

Basically, you can do a conversion yourself manually along the lines of:基本上,您可以按照以下方式手动进行转换:

Document doc = new org.bson.Document();
doc.put("userName", user.getName());
doc.put("userId", user.getID());
// ... or whatever your user object looks like
// and then:
dbCollection.insert(doc);

Then, you could try external encoding libraries for converting your object to JSON, for example Jackson as detailed in the answer of this question: Converting Java objects to JSON with Jackson然后,您可以尝试使用外部编码库将您的对象转换为 JSON,例如 Jackson,如此问题的答案中所述: Converting Java objects to JSON with Jackson

Once you have a JSON string, you can convert it to an org.bson.Document via一旦你有一个 JSON 字符串,你可以将它转换为 org.bson.Document 通过

org.bson.Document.parse(jsonString)

and write this into the database.并将其写入数据库。

Try using MongoTemplate.尝试使用 MongoTemplate。 Save the java object in mongodb using this template, it will get created in a document form.使用此模板将 java 对象保存在 mongodb 中,它将以文档形式创建。

https://www.mkyong.com/mongodb/spring-data-mongodb-insert-document/ https://www.mkyong.com/mongodb/spring-data-mongodb-insert-document/

Example例子

MongoTemplate mongoTemplate = new MongoTemplate(new MongoClient("<server>"),"<db name>");

User user = new NormalUser();
mongoTemplate.save(user, "<collection>");

Here is the detailed analysis on this issue:-以下是对这个问题的详细分析:-

Looks like "lombok" library adds the boilerplate code (ie getter and setter methods for the attributes) during compilation time.看起来“lombok”库在编译时添加了样板代码(即属性的getter 和setter 方法)。 I have observed two behaviors while executing the program.我在执行程序时观察到两种行为。

1) Eclipse behavior:- 1) Eclipse 行为:-

When I run the program via IDE (eg eclipse), the "getter" and "setter" methods were not getting generated.当我通过 IDE(例如 eclipse)运行程序时,没有生成“getter”和“setter”方法。 I have got serialization error when I ran the main class.运行主类时出现序列化错误。 I have decompiled the classes User and NormalUser and checked the content.我已经反编译了 User 和 NormalUser 类并检查了内容。 It doesn't have the "getter" and "setter" methods.它没有“getter”和“setter”方法。

Online Java Decompiler在线 Java 反编译器

2) Maven behavior:- 2) Maven 行为:-

I have used maven commands to build the project and checked the classes User and NormalUser.我已经使用 maven 命令来构建项目并检查类 User 和 NormalUser。 This time I can see the boilerplate codes being generated.这次我可以看到正在生成的样板代码。 I have executed my Main class and it worked fine.我已经执行了我的 Main 类并且运行良好。

Solution:-解决方案:-

MongoClient client = new MongoClient();
        MongoDatabase database = client.getDatabase("localhost");
        MongoCollection<Document> normalUserCollection = database.getCollection("normaluser");

        User normalUser = new NormalUser("jack", "mike", "US", "dni", "123", Gender.MALE);

        Document document = new Document();
        document.put("user", document.parse(new ObjectMapper().writeValueAsString(normalUser)));

Mongo Java Driver used:-使用的 Mongo Java 驱动程序:-

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.5</version>
        </dependency>

Output:-输出:-

The document has been inserted successfully in MongoDB collection.该文档已成功插入到 MongoDB 集合中。

{
    "_id" : ObjectId("57d2e4134c1c7b287cde1d30"),
    "user" : {
        "surname" : "mike",
        "address" : "US",
        "dni" : "dni",
        "bankAccount" : "123",
        "admin" : false,
        "name" : "jack",
        "gender" : "MALE"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM