POJO to org.bson.Document and Vice Versa

时间:2016-09-04 19:43:40

标签: java mongodb-java

有没有一种简单的方法可以将Simple POJO转换为org.bson.Document?

我知道有很多方法可以像这样做:

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

但它有一个更简单和更错误的方式吗?

7 个答案:

答案 0 :(得分:10)

目前,Mongo Java Driver 3.9.1提供了开箱即用的POJO支持 http://mongodb.github.io/mongo-java-driver/3.9/driver/getting-started/quick-start-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。注释您的POJOS

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;
    }
}

第3。查询mongoDB并获取POJOS

MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());


就是这样!!!您可以轻松获得POJOS 没有繁琐的手动映射 并且没有失去运行本地mongo查询的能力

答案 1 :(得分:5)

您可以使用GsonDocument.parse(String json)将POJO转换为Document。这适用于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);
    }

}

答案 2 :(得分:4)

重点是,你不需要把手放在org.bson.Document上。

Morphia会在幕后为你做所有这些。

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);

在这里您可以找到几个示例:https://mongodb.github.io/morphia/

答案 3 :(得分:1)

我不知道您的MongoDB版本。但是如今,无需将Document转换为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);

如果您想使用POJO,请确保您的Mongo数据库配置了正确的编解码器。

MongoClient mongoClient = new MongoClient();
//This registry is required for your Mongo document to POJO conversion
CodecRegistry codecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
        fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoDatabase db = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry);

答案 4 :(得分:1)

如果你在 springboot 中使用 Spring Data MongoDB,MongoTemplate 有一个方法可以很好地做到这一点。

Spring Data MongoDB API

这是一个示例。

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>

应用程序.yml

# mongodb config
spring:
  data:
    mongodb:
      uri: mongodb://your-mongodb-url

答案 5 :(得分:0)

如果您使用的是Morphia,则可以使用这段代码将POJO转换为文档。

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

如果您不使用Morphia,则可以通过编写自定义映射并将POJO转换为DBObject,然后将DBObject进一步转换为字符串然后进行解析来进行同样的操作。

答案 6 :(得分:0)

不,我认为对于bulkInsert可能有用。我认为bulkInsert无法与pojo一起使用(如果我没记错的话)。 如果有人知道如何使用bulkInsert