中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java中獲取MongoDB連接的方法詳解

發布時間:2020-10-19 08:58:34 來源:腳本之家 閱讀:223 作者:德邦總管 欄目:編程語言

首先是所需jar包,Maven中的配置如下:

<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()三個參數分別為 用戶名 數據庫名稱 密碼 
MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "123456Ab".toCharArray()); 
List<MongoCredential> credentials = new ArrayList<MongoCredential>(); 
credentials.add(credential); 
//通過連接認證獲取MongoDB連接 
MongoClient mongoClient = new MongoClient(addrs,credentials); 
//連接到數據庫 
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
mongoDatabase.getCollection("test").find().iterator();
// 關閉數據庫連接
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)兩個參數分別為 IP地址 端口號
    ServerAddress serverAddress = new ServerAddress(host,port); 
    List<ServerAddress> addrs = new ArrayList<ServerAddress>(); 
    addrs.add(serverAddress);
      
    //MongoCredential.createScramSha1Credential(username,source,password)三個參數分別為 用戶名 數據庫名稱 密碼 
    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;
  }
   
  /**
   * 插入數據
   */
  @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插入數據成功,集合為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插入數據成功,集合為col,文檔為:"+mongoTemplate.getCollection("col"));
  }
   
  /**
   * 查詢所有
   */
  @Test
  public void findAll(){
    List<ShopDO> list = mongoTemplate.findAll(ShopDO.class,"col");
    System.out.println("mongoDB查詢數據成功,集合為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查詢數據成功,集合為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")); //結果集進行排序
    query.with(sort);
    List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col");
    System.out.println("mongoDB組合查詢數據成功,集合為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分頁查詢下標為1開始總共3行數據,集合為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查詢名稱叫菜鳥的數據成功,集合為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更新數據成功,集合為col,行數為:" + 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的數據成功,集合為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更新數據成功,集合為col,行數為:" + 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刪除數據成功,集合為col,行數為:" + result.getN() + "刪除的ID為"+result.getUpsertedId());
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

奉化市| 台安县| 盐山县| 滁州市| 虎林市| 财经| 金乡县| 疏勒县| 个旧市| 义乌市| 凤冈县| 芜湖市| 尉氏县| 翁牛特旗| 伊宁市| 永春县| 儋州市| 乡城县| 准格尔旗| 宜黄县| 方城县| 石棉县| 天水市| 临夏市| 台北县| 三穗县| 鱼台县| 宜宾县| 五莲县| 涿州市| 城固县| 新泰市| 东港市| 洛扎县| 庆城县| 张家港市| 桃园县| 孟津县| 达日县| 许昌市| 三原县|