java POJO 到 org.bson.Document,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39320825/
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
POJO to org.bson.Document and Vice Versa
提问by yesterdaysfoe
Is there a simple way to convert Simple POJO to org.bson.Document?
有没有一种简单的方法可以将 Simple POJO 转换为 org.bson.Document?
I'm aware that there are ways to do this like this one:
我知道有很多方法可以做到这一点:
Document doc = new Document();
doc.append("name", person.getName()):
But does it have a much simpler and typo less way?
但它有更简单和更少错字的方法吗?
采纳答案by midnight
The point is, that you do not need to put your hands on org.bson.Document.
关键是,您不需要将手放在 org.bson.Document 上。
Morphia will do all that for you behind the curtain.
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);
Here you will find several examples: https://mongodb.github.io/morphia/
在这里你会发现几个例子:https: //mongodb.github.io/morphia/
回答by kamildab_84
Currently Mongo Java Driver 3.9.1 provide POJO support out of the box
http://mongodb.github.io/mongo-java-driver/3.9/driver/getting-started/quick-start-pojo/
Let's say you have such example collection with one nested object
目前 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. Provide a MongoDatabase bean with proper CodecRegistry
1. 提供一个带有适当 CodecRegistry 的 MongoDatabase bean
@Bean
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://username:[email protected]: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. Annotate your POJOS
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. Query mongoDB and obtain POJOS
3.查询mongoDB,获取POJOS
MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());
And that's it !!! You can easily obtain your POJOS
without cumbersome manual mappings
and without loosing ability to run native mongo queries
就是这样!!!您可以轻松获取 POJOS,无需繁琐的手动映射,也无需失去运行本机 mongo 查询的能力
回答by jacobcs
You can use Gson
and Document.parse(String json)
to convert a POJO to a Document
. This works with the version 3.4.2 of java driver.
您可以使用Gson
和Document.parse(String json)
将 POJO 转换为Document
. 这适用于 java 驱动程序的 3.4.2 版。
Something like this:
像这样的东西:
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);
}
}
回答by RLD
I don't know your MongoDB version. But now-a-days, there is no need to convert Document to POJO or vice versa. You just need to create your collection depending on what you want to work with, Document or POJO as follows.
我不知道你的 MongoDB 版本。但是现在,没有必要将 Document 转换为 POJO,反之亦然。您只需要根据您要使用的内容,Document 或 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);
Please ensure your Mongo DB is configured with proper codecregistry if you want to use POJO.
如果您想使用 POJO,请确保您的 Mongo DB 配置了正确的 codecregistry。
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);
回答by Abhishek Deora
If you are using Morphia, you can convert a POJO to document using this piece of code.
如果您使用的是 Morphia,您可以使用这段代码将 POJO 转换为文档。
Document document = Document.parse( morphia.toDBObject( Entity ).toString() )
If you are not using Morphia, then you can do the same by writing custom mapping and converting the POJO into a DBObject and further converting the DBObject to a string and then parsing it.
如果您不使用 Morphia,那么您可以通过编写自定义映射并将 POJO 转换为 DBObject 并进一步将 DBObject 转换为字符串然后解析它来执行相同操作。