2016-09-04 4 views
3

Gibt es eine einfache Möglichkeit, einfache POJO in org.bson.Document zu konvertieren?POJO zu org.bson.Document und Vice Versa

mir bewusst bin, dass es Wege gibt, dies so zu tun:

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

Aber hat es eine viel einfachere und weniger Weise Typo?

Antwort

2

Der Punkt ist, dass Sie nicht Ihre Hände auf org.bson.Document legen müssen.

Morphia wird all das für Sie hinter dem Vorhang tun.

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

Hier finden Sie einige Beispiele finden: https://mongodb.github.io/morphia/

0

Sie können Morphia verwenden, um Ihre POJOs für Sie zu speichern/laden. Wenn alles wie geplant abläuft, unterstützt der Java-Treiber dieses Mapping nativ.

+0

können Sie ein Beispiel geben? – yesterdaysfoe

1

Sie Gson und Document.parse(String json) können Sie eine POJO zu einem Document konvertieren. Dies funktioniert mit der Version 3.4.2 des Java-Treibers.

Etwas wie folgt aus:

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

} 
Verwandte Themen