2016-05-12 35 views
0

我需要爲java中的MongoDB創建一個DataSource實現,就像在java.sql.DataSource中可以在MongoDB中實現這樣的事情嗎?如果有的話,任何人都可以給我一些提示或線索,我該如何實現?在Java中爲MongoDB創建數據源

+0

爲什麼你不能使用現有的?例如,請參閱http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/ –

回答

0

您不需要爲已經在其API中創建的MongoDB使用數據源。

public static MongoClient mongoClient; 
public static DB db; 
public static DBCollection collection; 

public static void setupDB() throws UnknownHostException { 
    mongoClient = new MongoClient("localhost", port); 

    db = mongoClient.getDB("Your Database"); 

    collection = db.getCollection("Collection Name"); 

} 

這會將您連接到數據庫並保存客戶端連接。無論何時您需要從您正在使用的集合中調用某些東西,只需使用即可。

collection.(command here) 

根據您的MongoDB的驅動程序的版本取決於是否需要爲database.If的用戶名和密碼,您想使用的認證只是看到這個鏈接:http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/authenticating/

或者找一個較新的更新的參考文獻