首先是所需jar包,Maven中的配置如下:
成都創(chuàng)新互聯(lián)主要從事網(wǎng)站制作、做網(wǎng)站、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)融安,十年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108
<dependency> <groupId>org.MongoDB</groupId> <artifactId>mongodb-driver</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.7.0.RELEASE</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.9.1</version> </dependency>
獲取連接的代碼如下(本中用的是模板類):
List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(new ServerAddress(dataSource.getSourceIp(), Integer.valueOf(dataSource.getSourcePort()))); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(MongoCredential.createScramSha1Credential(dataSource.getUsername(), dataSource.getSourceName(), dataSource.getPassword().toCharArray())); MongoClient mongoClient = new MongoClient(addrs, credentials); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, dataSource.getSourceName()); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory); mongoTemplate.getCollectionNames();
或者用如下方式獲取:
ServerAddress serverAddress = new ServerAddress("192.168.16.121",27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三個參數(shù)分別為 用戶名 數(shù)據(jù)庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "123456Ab".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通過連接認證獲取MongoDB連接 MongoClient mongoClient = new MongoClient(addrs,credentials); //連接到數(shù)據(jù)庫 MongoDatabase mongoDatabase = mongoClient.getDatabase("admin"); mongoDatabase.getCollection("test").find().iterator(); // 關(guān)閉數(shù)據(jù)庫連接 mongoClient.close();
附帶簡單增刪改查的例子:
package test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.junit.Test; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.WriteResult; import bean.Book; import bean.Good; import bean.ShopDO; import net.sf.json.JSONObject; public class MongoTemplateTest { public static MongoTemplate mongoTemplate = getMongoTemplate(); public static void main(String[] args) { System.out.println(mongoTemplate.getCollectionNames()); } public static MongoTemplate getMongoTemplate(){ String host = "192.168.16.121"; int port = 27017; String databaseName = "test"; String username = "root"; String password = "123456Ab"; //ServerAddress(host,port)兩個參數(shù)分別為 IP地址 端口號 ServerAddress serverAddress = new ServerAddress(host,port); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential(username,source,password)三個參數(shù)分別為 用戶名 數(shù)據(jù)庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential(username, databaseName, password.toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通過連接認證獲取MongoDB連接 MongoClient mongoClient = new MongoClient(addrs,credentials); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, databaseName); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory); return mongoTemplate; } /** * 插入數(shù)據(jù) */ @Test public void save(){ ShopDO shop1 = new ShopDO(100L,"菜鳥教程"); ShopDO shop2 = new ShopDO(101L,"有道筆記"); mongoTemplate.save(shop1,"col"); mongoTemplate.save(shop2,"col"); System.out.println("mongoDB插入數(shù)據(jù)成功,集合為col,文檔為:"+mongoTemplate.getCollection("col")); } @Test public void save1(){ Book book = new Book(22L,"英語","32.5"); mongoTemplate.save(book,"col"); } @Test public void save2(){ Good good = new Good(new HashMap<String,String>(){{put("id","1");put("name","動物");}}); mongoTemplate.save(good,"col"); } @Test public void save3(){ mongoTemplate.save(JSONObject.fromObject("{\"這樣\":\"we\",\"好吧\":\"hai\"}"),"col"); System.out.println("mongoDB插入數(shù)據(jù)成功,集合為col,文檔為:"+mongoTemplate.getCollection("col")); } /** * 查詢所有 */ @Test public void findAll(){ List<ShopDO> list = mongoTemplate.findAll(ShopDO.class,"col"); System.out.println("mongoDB查詢數(shù)據(jù)成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 單條件查詢 */ @Test public void simpleQuery(){ Query query = Query.query(Criteria.where("no").is(100L)); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB按條件ID查詢數(shù)據(jù)成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 多條件查詢 */ @Test public void muchQuery(){ Criteria criteria = new Criteria(); //or是條件或查詢,and是條件與查詢 criteria.orOperator( Criteria.where("no").is(100), Criteria.where("name").is("菜鳥教程")); Query query = new Query(criteria); //組合查詢放入query Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC,"no")); //結(jié)果集進行排序 query.with(sort); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB組合查詢數(shù)據(jù)成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 分頁查詢 */ @Test public void LimitQuery(){ Query query = new Query(); query.skip(1).limit(3); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB分頁查詢下標(biāo)為1開始總共3行數(shù)據(jù),集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 模糊查詢 */ @Test public void LikeQuery(){ Query query = new Query(Criteria.where("name").regex("菜鳥")); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB查詢名稱叫菜鳥的數(shù)據(jù)成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } Update update = new Update(); update.set("name","菜鳥教程old"); WriteResult wr = mongoTemplate.updateMulti(query,update,"col"); System.out.println("mongoDB更新數(shù)據(jù)成功,集合為col,行數(shù)為:" + wr.getN()); } /** * 更新 */ @Test public void update(){ Query query = new Query(Criteria.where("no").is(100)); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB查詢no為100的數(shù)據(jù)成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } Update update = new Update(); update.set("name","菜鳥教程new"); WriteResult wr = mongoTemplate.updateFirst(query,update,"col"); System.out.println("mongoDB更新數(shù)據(jù)成功,集合為col,行數(shù)為:" + wr.getN()); } /** * 刪除 */ @Test public void delete(){ Query query = new Query(Criteria.where("no").is(1)); WriteResult result = mongoTemplate.remove(query, "col"); System.out.println("mongoDB刪除數(shù)據(jù)成功,集合為col,行數(shù)為:" + result.getN() + "刪除的ID為"+result.getUpsertedId()); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
標(biāo)題名稱:Java中獲取MongoDB連接的方法詳解
路徑分享:http://m.newbst.com/article6/pogsog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、域名注冊、移動網(wǎng)站建設(shè)、全網(wǎng)營銷推廣、手機網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)