2016-01-28 36 views
2

Mongo Java驅動程序3添加了對Codec infrastructure的支持,我在下面嘗試。默認情況下,它帶有以下3個對象的編解碼器:Document,BasicDBObject和BsonDocument。Mongo Java驅動程序3 - 使用擴展對象'Document'

我想通過讓我的類MyClass擴展Document來做一件很簡單的事情。但是,它會失敗並顯示內聯錯誤。

我發現這個gist但它似乎過於複雜..是否沒有簡單的方法註冊MyClass作爲一個編解碼器,因爲它也是一個文檔?

謝謝。 -henning

public class PlayMongo { 
    static class MyClass extends Document { 
     public MyClass(String key, Object value) { 
      super(key, value); 
     } 
    } 

    public static void main(String[] args) { 
     MongoClient mongoClient = new MongoClient(); 
     MongoDatabase db = mongoClient.getDatabase("test"); 

     // Works like a charm 
     MongoCollection<Document> documentCollection = db.getCollection("docs"); 
     documentCollection.insertOne(new Document().append("hello", "world")); 

     // Fails with CodecConfigurationException: Can't find a codec for class play.reactivemongo.PlayMongo$MyClass 
     MongoCollection<MyClass> myClassCollection = db.getCollection("myclasses", MyClass.class); 
     myClassCollection.insertOne(new MyClass("hello", "world")); 
    } 
} 

回答

1

最簡單的方法,使其使用Morphia。 Morphia準備將Java對象映射到MongoDB集合。我做了一個例子,你可以看到它是如何工作的。在這個例子中,MongoDB有一個名爲people的集合,映射到一個名爲Person的Java類。該Person看起來是這樣的:

@Entity("people") 
public class Person { 
    private String firstName; 
    private String lastName; 

    //obrigactory constructor for Morphia 
    public Person() { 
    } 

    public Person(String firstName, String lastName) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    @Override 
    public String toString() { 
     return firstName + " " + lastName; 
    } 

} 

嗎啡知道一個Person對象對應於人收藏,因爲Entity註釋。它還需要一個沒有參數的構造函數來正確轉換對象,所以我們爲什麼要在那裏有一個。

MongoDB Java Driver已經非常簡單了,但Morphia使得CRUD操作變得更簡單。接下來的代碼塊將插入並在數據庫中檢索一個人:

 Morphia morphia = new Morphia(); 
     Datastore datastore = morphia.createDatastore(new MongoClient(), "test"); 

     Person johnDoe = new Person("John", "Doe"); 

     //saves John Doe on DB 
     datastore.save(johnDoe); 

     //retrieves all people whose first name is John 
     List<Person> people = datastore.createQuery(Person.class).filter("firstName", "John").asList(); 

     System.out.println(people.size()); //prints 1 
     Person person = people.get(0); 

     System.out.println(person); //prints John Doe 

正如你可以看到,我們只需要說哪個Java類將被用於再嗎啡可以根據註釋發現權集合它發現。之後,一個簡單的save它足以將對象插入數據庫。檢索數據基本上是相同的過程:告知您想要的課程以及您的過濾器。

請務必記住,Morphia會帶來額外的性能成本。在大多數情況下,這不會有什麼區別,但是您需要評估自己的場景並運行一些自己的測試。

+0

這樣做..我喜歡它,因爲它很乾淨。謝謝丹尼爾! –

0

我創建了一個小型庫,用於爲POJO自動創建編解碼器。如果你不想用大圖書館像嗎啡,檢查它在:

https://github.com/dozd/mongo-mapper

它適用於同步以及新蒙戈驅動異步版本。

相關問題