2016-11-27 60 views
0

我有一個名爲Status的Java類,它由3個字段組成:字符串電子郵件,字符串狀態,ArrayList(評論)commentList。 Comment是由2個字符串字段組成的另一個Java類。我曾與MySQL合作過,並且我知道如何將這個Status對象保存在數據庫表中。現在我正在學習MongoDB,我需要這個Status對象來存儲在我的數據庫集合中。我該怎麼做?截至目前,我已經嘗試了以下內容並未能存儲狀態對象。任何人都可以幫我一下嗎? 我曾嘗試以下:如何在MongoDB集合中保存包含對象列表的對象

public static MongoClient getMongoConnection() { 
    MongoClient mongo = null; 
    try { 
     mongo = new MongoClient("localhost", 27017); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return mongo; 
} 

public static void main(String[] args) { 
MongoClient mongo = getMongoConnection(); 
     DB db = mongo.getDB("myTestdatabase"); 
     DBCollection myReviews = db.getCollection("myStatus"); 
BasicDBObject obj = new BasicDBObject(); 

    List<Object> commentList = new BasicDBList(); 
    commentList.add(new Comment("Looks like a nice status", "[email protected]")); 
    commentList.add(new Comment("This is a nice status", "[email protected]")); 


    Status status = new Status(); 
    status.setStatus("This is my new Status"); 
    status.setEmail("[email protected]"); 


    obj.put("status", status.getStatus()); 
    obj.put("email", status.getEmail()); 
    obj.put("comments", commentList); 
     myReviews.insert(obj); 

}

我得到這個錯誤。

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.Comment. 
+0

你會得到什麼錯誤? – Veeram

+0

org.bson.codecs.configuration.CodecConfigurationException:找不到類com.Comment的編解碼器。 –

+0

MongoDB只能處理Bson類型。而不是將註釋對象添加到dbList。從每條評論中創建一個dbobject並將它們添加到列表中,就像您對狀態對象所做的一樣。 – Veeram

回答

0

mongo.getDB折舊。使用下面的來創建你的數據庫。確保你還導入了bson。

MongoClient mongo = new MongoClient("localhost", 27017);   
MongoDatabase db = mongo.getDatabase("myDB"); 
MongoCollection items = db.getCollection("myCollection"); 

Document document = new Document(); // Create the document to be inserted to the DB 
document.put("First Name", "John"); 
document.put("Last Name", "Smith"); 

items.insertOne(document); // Insert document to DB 
+0

沒有這個工作。仍然是例外。 org.bson.codecs.configuration.CodecConfigurationException:找不到類com.Comment的編解碼器 –

相關問題