Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java POJO到org.bson.Document,反之亦然_Java_Mongodb Java - Fatal编程技术网

Java POJO到org.bson.Document,反之亦然

Java POJO到org.bson.Document,反之亦然,java,mongodb-java,Java,Mongodb Java,有没有简单的方法将简单的POJO转换为org.bson.Document 我知道有这样的方法: Document doc = new Document(); doc.append("name", person.getName()): 但它是否有一种更简单、打字更少的方式呢?关键是,你不需要把手放在org.bson.Document上 莫菲娅会在幕后为你做这一切 import com.mongodb.MongoClient; import org.mongodb.morphia.Datastor

有没有简单的方法将简单的POJO转换为org.bson.Document

我知道有这样的方法:

Document doc = new Document();
doc.append("name", person.getName()):

但它是否有一种更简单、打字更少的方式呢?

关键是,你不需要把手放在org.bson.Document上

莫菲娅会在幕后为你做这一切

import com.mongodb.MongoClient;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.DatastoreImpl;
import org.mongodb.morphia.Morphia;
import java.net.UnknownHostException;

.....
    private Datastore createDataStore() throws UnknownHostException {
        MongoClient client = new MongoClient("localhost", 27017);
        // create morphia and map classes
        Morphia morphia = new Morphia();
        morphia.map(FooBar.class);
        return new DatastoreImpl(morphia, client, "testmongo");
    }

......

    //with the Datastore from above you can save any mapped class to mongo
    Datastore datastore;
    final FooBar fb = new FooBar("hello", "world");
    datastore.save(fb);

这里有几个例子:

您可以使用
Gson
Document.parse(字符串json)
将POJO转换为
文档。这适用于java驱动程序的3.4.2版本

大概是这样的:

package com.jacobcs;

import org.bson.Document;

import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoLabs {

    public static void main(String[] args) {
        // create client and connect to db
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("my_db_name");

        // populate pojo
        MyPOJO myPOJO = new MyPOJO();
        myPOJO.setName("MyName");
        myPOJO.setAge("26");

        // convert pojo to json using Gson and parse using Document.parse()
        Gson gson = new Gson();
        MongoCollection<Document> collection = database.getCollection("my_collection_name");
        Document document = Document.parse(gson.toJson(myPOJO));
        collection.insertOne(document);
    }

}
package com.jacobcs;
导入org.bson.Document;
导入com.google.gson.gson;
导入com.mongodb.MongoClient;
导入com.mongodb.client.MongoCollection;
导入com.mongodb.client.MongoDatabase;
公开课{
公共静态void main(字符串[]args){
//创建客户端并连接到数据库
MongoClient MongoClient=新的MongoClient(“本地主机”,27017);
MongoDatabase=mongoClient.getDatabase(“我的数据库名称”);
//填充pojo
MyPOJO MyPOJO=新的MyPOJO();
myPOJO.setName(“MyName”);
myPOJO.setAge(“26”);
//使用Gson将pojo转换为json,并使用Document.parse()进行解析
Gson Gson=新的Gson();
MongoCollection collection=database.getCollection(“我的收藏名”);
Document=Document.parse(gson.toJson(myPOJO));
收藏.插入器(文件);
}
}

目前,Mongo Java驱动程序3.9.1提供了现成的POJO支持

假设您有这样一个示例集合,其中包含一个嵌套对象

db.createCollection("product", {
validator: {
    $jsonSchema: {
        bsonType: "object",
        required: ["name", "description", "thumb"],
        properties: {
            name: {
                bsonType: "string",
                description: "product - name - string"
            },
            description: {
                bsonType: "string",
                description: "product - description - string"
            },
            thumb: {
                bsonType: "object",
                required: ["width", "height", "url"],
                properties: {
                    width: {
                        bsonType: "int",
                        description: "product - thumb - width"
                    },
                    height: {
                        bsonType: "int",
                        description: "product - thumb - height"
                    },
                    url: {
                        bsonType: "string",
                        description: "product - thumb - url"
                    }
                }
            }

        }
    }
}});
1。为MongoDatabase bean提供适当的CodecRegistry

@Bean
public MongoClient mongoClient() {
    ConnectionString connectionString = new ConnectionString("mongodb://username:password@127.0.0.1:27017/dbname");

    ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings.builder()
            .minSize(2)
            .maxSize(20)
            .maxWaitQueueSize(100)
            .maxConnectionIdleTime(60, TimeUnit.SECONDS)
            .maxConnectionLifeTime(300, TimeUnit.SECONDS)
            .build();

    SocketSettings socketSettings = SocketSettings.builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();

    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .applyConnectionString(connectionString)
            .applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings))
            .applyToSocketSettings(builder -> builder.applySettings(socketSettings))
            .build();

    return MongoClients.create(clientSettings);
}

@Bean 
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
    CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();
    CodecRegistry fromProvider = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(defaultCodecRegistry, fromProvider);
    return mongoClient.getDatabase("dbname").withCodecRegistry(pojoCodecRegistry);
}
2。为您的POJO添加注释

public class ProductEntity {

    @BsonProperty("name") public final String name;
    @BsonProperty("description") public final String description;
    @BsonProperty("thumb") public final ThumbEntity thumbEntity;

    @BsonCreator
    public ProductEntity(
            @BsonProperty("name") String name,
            @BsonProperty("description") String description,
            @BsonProperty("thumb") ThumbEntity thumbEntity) {
        this.name = name;
        this.description = description;
        this.thumbEntity = thumbEntity;
    }
}

public class ThumbEntity {

    @BsonProperty("width") public final Integer width;
    @BsonProperty("height") public final Integer height;
    @BsonProperty("url") public final String url;

    @BsonCreator
    public ThumbEntity(
            @BsonProperty("width") Integer width,
            @BsonProperty("height") Integer height,
            @BsonProperty("url") String url) {
        this.width = width;
        this.height = height;
        this.url = url;
    }
}
MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());
3。查询mongoDB并获取POJO

public class ProductEntity {

    @BsonProperty("name") public final String name;
    @BsonProperty("description") public final String description;
    @BsonProperty("thumb") public final ThumbEntity thumbEntity;

    @BsonCreator
    public ProductEntity(
            @BsonProperty("name") String name,
            @BsonProperty("description") String description,
            @BsonProperty("thumb") ThumbEntity thumbEntity) {
        this.name = name;
        this.description = description;
        this.thumbEntity = thumbEntity;
    }
}

public class ThumbEntity {

    @BsonProperty("width") public final Integer width;
    @BsonProperty("height") public final Integer height;
    @BsonProperty("url") public final String url;

    @BsonCreator
    public ThumbEntity(
            @BsonProperty("width") Integer width,
            @BsonProperty("height") Integer height,
            @BsonProperty("url") String url) {
        this.width = width;
        this.height = height;
        this.url = url;
    }
}
MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());
MongoCollection collection=mongoDatabase.getCollection(“产品”);
单据查询=新建单据();
List products=collection.find(query,ProductEntity.class).into(new ArrayList());

就这样!!!您可以轻松获得您的POJO 没有繁琐的手动映射
如果您使用的是Morphia,在不丧失运行本机mongo查询的能力的情况下,您可以使用这段代码将POJO转换为文档

Document document = Document.parse( morphia.toDBObject( Entity ).toString() )

如果您没有使用Morphia,那么您也可以编写自定义映射,将POJO转换为DBObject,然后将DBObject进一步转换为字符串,然后对其进行解析。

我不知道您的MongoDB版本。但现在,不需要将文档转换为POJO,也不需要将文档转换为POJO。您只需根据需要使用的文档或POJO创建集合,如下所示

//If you want to use Document
MongoCollection<Document> myCollection = db.getCollection("mongoCollection");
Document doc=new Document();
doc.put("name","ABC");
myCollection.insertOne(doc);


//If you want to use POJO
MongoCollection<Pojo> myCollection = db.getCollection("mongoCollection",Pojo.class);
Pojo obj= new Pojo();
obj.setName("ABC");
myCollection.insertOne(obj);

不,我想这对我来说是有用的。我认为bulkInsert不能与pojo一起工作(如果我没有弄错的话)。
如果有人知道如何使用bulkInsert,如果您将Spring数据MongoDB与springboot结合使用,MongoTemplate有一种方法可以很好地做到这一点

这是一个样品

1.在spring boot项目中,首先自动连接mongoTemplate

@Autowired
MongoTemplate mongoTemplate;
2.在您的服务中使用mongoTemplate

Document doc = new Document();
mongoTemplate.getConverter().write(person, doc);
为此,需要配置pom文件和yml以注入mongotemplate

pom.xml

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>2.1.10.RELEASE</version>
</dependency>

它们不是必需的,请看一看:然而,在我看来,注释真的很棒,因为:-您可以使POJO对象不可变,这始终是一个很好的实践-不可变对象使代码不那么容易出错,并且您摆脱了所有这些getter和setter-当mongo中的字段名更改时,您可以轻松地更改其注释,在POJO objectIs中不涉及字段名的情况下,我们可以将其用于非嵌套类,但是那些具有对不同类的对象引用的类?我已经使用
@Field
注释将它们映射到了我的数据库。这是否适用于抽象类和继承?如果使用Long,Gson不会处理bson期望看到的时间。示例:a=int,b=long应该以{“a”:12,b:{“$numberLong”:“14”}结尾,但看起来所有值都被添加为“a”。这并不能真正回答问题。如果您有不同的问题,可以通过单击“提问:”来提问。一旦你有了足够的声誉,你也可以增加一笔赏金来吸引更多的注意力:请给你的答案添加一些解释。@YLR嗨,我更新了我的答案,谢谢