溫馨提示×

溫馨提示×

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

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

Spring Boot如何集成mongodb數(shù)據(jù)庫

發(fā)布時間:2020-07-27 09:49:49 來源:億速云 閱讀:159 作者:小豬 欄目:編程語言

這篇文章主要講解了Spring Boot如何集成mongodb數(shù)據(jù)庫,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

一.認(rèn)識mongodb

MongoDB是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。它支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似json的bson格式,因此可以存儲比較復(fù)雜的數(shù)據(jù)類型。Mongo最大的特點是它支持的查詢語言非常強(qiáng)大,其語法有點類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實現(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能,而且還支持對數(shù)據(jù)建立索引。

二.Spring boot項目集成mongodb

1.添加mongodb依賴

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

2.配置mongodb的連接

spring:
data:
mongodb:
#uri: mongodb://localhost:27017/data_exploration
uri: mongodb://root:dhcc-mongodb@192.168.100.87:27017/data_exploration authSource=admin&authMechanism=SCRAM-SHA-1

解析:以上uri分別代表本地配置和遠(yuǎn)程連接

3.操作數(shù)據(jù)庫

(1)保存

@Repository
public class ExplorationJobDao {

  @Autowired
  MongoTemplate mongoTemplate;

  public void save(ExplorationJob explorationJob) {
    mongoTemplate.save(explorationJob);
  }
}

(2)根據(jù)ID修改一條數(shù)據(jù)(其原理先符合ID的數(shù)據(jù),然后刪除查詢結(jié)果的第一條)

public void updateExecutionStatusById(int executionStatus, String jobId) {
      Query query = new Query(Criteria.where("jobId").is(jobId));
      Update update = new Update().set("executionStatus", executionStatus);
      mongoTemplate.updateFirst(query, update, ExplorationJob.class);
  }

(3)根據(jù)條修改多條數(shù)據(jù)(查詢符合ID的所有數(shù)據(jù),然后將所有數(shù)據(jù)修改)

public void update(BusinessExploration businessExploration) {
    Query query = new Query(Criteria.where("_id").is(businessExploration.getId()));
    Update update = new Update().set("sourceUnit", businessExploration.getSourceUnit())
        .set("appSystem", businessExploration.getAppSystem())
        .set("businessImplication", businessExploration.getBusinessImplication())
        .set("safetyRequire", businessExploration.getSafetyRequire());
    mongoTemplate.updateMulti(query, update, TableExploration.class);
  }

(4)刪除(根據(jù)ID刪除)

public void delExplorationJobById(String jobId) {
     Query query=new Query(Criteria.where("jobId").is(jobId));
     mongoTemplate.remove(query,ExplorationJob.class);
  }

(5)根據(jù)條件查詢(根據(jù)ID查詢)

public ExplorationJob getExplorationJobByJobId(String jobId) {
    Query query = new Query(Criteria.where("jobId").is(jobId));
    ExplorationJob explorationJob = mongoTemplate.findOne(query, ExplorationJob.class);
    return explorationJob;
  }

(6)查詢所有

mongoTemplate.findAll(TableExploration.class);

(7)多條件動態(tài)查詢

public List<ExplorationJob> getExplorationByCondition(ExplorationJob explorationJob) {
    Query query = new Query();
    if (explorationJob.getJobName() != null) {
       Pattern pattern = Pattern.compile("^.*" + explorationJob.getJobName() + ".*$", Pattern.CASE_INSENSITIVE);
       query.addCriteria(Criteria.where("jobName").regex(pattern));
    }
    if (explorationJob.getDsType() != null) {
      query.addCriteria(Criteria.where("dsType").is(explorationJob.getDsType()));
    }
    if (explorationJob.getExecutionStatus() != null) {
       query.addCriteria(Criteria.where("executionStatus").lte(explorationJob.getExecutionStatus()));
    }
    List<ExplorationJob> explorationJobs=mongoTemplate.find(query, ExplorationJob.class);
    return explorationJobs;
  }

(8)查詢最大值

public Date getMaxExplorationDate(String tableName) {
    FindIterable<Document> iterable = mongoTemplate.getCollection("tableExploration")
        .find(new BasicDBObject("tableName", tableName)).sort(new BasicDBObject("explorationDate", -1)).skip(0)
        .limit(1);
    Document doc =null;
    if (getDocuments(iterable).size()>0) {
      doc=getDocuments(iterable).get(0);
      Date date = doc.getDate("explorationDate");
      return date;
    }else {
      return null;
    }
  }

  /**
   * 工具方法
   * 
   * @param iterable
   * @return
   */
  public static List<Document> getDocuments(FindIterable<Document> iterable) {
    List<Document> results = new ArrayList<Document>();
    if (null != iterable) {
      MongoCursor<Document> cursor = iterable.iterator();
      Document doc = null;
      while (cursor.hasNext()) {
        doc = cursor.next();
        results.add(doc);
      }
    }
    return results;
  }

(9)分組查詢(這里還是用到了排序)

public List<TableExploration> getAllTableExplorationGroupByTableName(String jobId){
    Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.match(Criteria.where("jobId").is(jobId)),
        Aggregation.sort(new Sort(Direction.DESC,"explorationDate")),
        Aggregation.group("tableName")
        .first("_id").as("tableName")
        .first("databaseType").as("databaseType")
        .first("databaseName").as("databaseName")
        .first("networkSituation").as("networkSituation")
        .first("userName").as("userName")
        .first("password").as("password")
        .first("url").as("url")
        .first("dataStorage").as("dataStorage")
        .first("dataIncrement").as("dataIncrement")
        .first("explorationDate").as("explorationDate")
        //.push("columnExplorations").as("columnExplorations")
        .first("jobId").as("jobId")
        );
    AggregationResults<TableExploration> aggregationResults= mongoTemplate.aggregate(aggregation, "tableExploration", TableExploration.class);
    List<TableExploration> tableExplorations=aggregationResults.getMappedResults();
    return tableExplorations;

看完上述內(nèi)容,是不是對Spring Boot如何集成mongodb數(shù)據(jù)庫有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI