SpringBoot | 第三十一章:MongoDB的集成和使用

前言

上一章節,簡單講解了如何集成Spring-data-jpa。本章節,咱們來看看如何集成NoSQLMongodbmongodb是最先熱門非關係數據庫的之一,使用也比較廣泛。最適合來存儲一些非結構數據了,適合對大量或者無固定格式的數據進行存儲,好比:日誌、緩存等。html

一點知識

如下部分關於Mongodb介紹,來自網站:https://www.mongodb.com/cn純潔的微笑java

MongoDB簡介

MongoDB(來自於英文單詞「Humongous」,中文含義爲「龐大」)是能夠應用於各類規模的企業、各個行業以及各種應用程序的開源數據庫。做爲一個適用於敏捷開發的數據庫,MongoDB的數據模式能夠隨着應用程序的發展而靈活地更新。與此同時,它也爲開發人員 提供了傳統數據庫的功能:二級索引,完整的查詢系統以及嚴格一致性等等。 MongoDB可以使企業更加具備敏捷性和可擴展性,各類規模的企業均可以經過使用MongoDB來建立新的應用,提升與客戶之間的工做效率,加快產品上市時間,以及下降企業成本。git

**MongoDB是專爲可擴展性,高性能和高可用性而設計的數據庫。**它能夠從單服務器部署擴展到大型、複雜的多數據中心架構。利用內存計算的優點,MongoDB可以提供高性能的數據讀寫操做。 MongoDB的本地複製和自動故障轉移功能使您的應用程序具備企業級的可靠性和操做靈活性。github

簡單來講,MongoDB是一個基於分佈式文件存儲的數據庫,它是一個介於關係數據庫和非關係數據庫之間的產品,其主要目標是在鍵/值存儲方式(提供了高性能和高度伸縮性)和傳統的RDBMS系統(具備豐富的功能)之間架起一座橋樑,它集二者的優點於一身。web

MongoDB支持的數據結構很是鬆散,是相似jsonbson格式,所以能夠存儲比較複雜的數據類型,也由於他的存儲格式也使得它所存儲的數據在Nodejs程序應用中使用很是流暢。spring

傳統的關係數據庫通常由數據庫(database)、表(table)、記錄(record)三個層次概念組成,MongoDB是由數據庫(database)、集合(collection)、文檔對象(document)三個層次組成。MongoDB對於關係型數據庫裏的表,可是集合中沒有列、行和關係概念,這體現了模式自由的特色。sql

MongoDB中的一條記錄就是一個文檔,是一個數據結構,由字段和值對組成。MongoDB文檔與JSON對象相似。字段的值有可能包括其它文檔、數組以及文檔數組。MongoDB支持OS X、Linux及Windows等操做系統,並提供了Python,PHP,Ruby,Java及C++語言的驅動程序,社區中也提供了對Erlang及.NET等平臺的驅動程序。mongodb

MongoDB的適合對大量或者無固定格式的數據進行存儲,好比:日誌、緩存等。對事物支持較弱,不適用複雜的多文檔(多表)的級聯查詢。數據庫

SpringBoot集成MongoDB

得力於SpringBoot方便性,集成MongoDB也是很簡單的。可經過三種方式進行訪問,分別是:原生Db對象MongoTemplate以及MongoRepository。原生的方式須要鏈接其語法規則,這裏就不闡述了,畢竟不熟悉。仍是使用封裝好的吧,開箱急用!json

準備工做

本文示例的MongoDB版本爲:4.0.3。 可視化工具爲:studio-3t-x64。

studio-3t

至於MongoDB如何安裝,你們簡單百度下就行了,很簡單。下載個msi,直接安裝便可。

**下載地址:**https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-4.0.3-signed.msi

0.加入POM依賴。

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

1.建立實體。

/**
 * 通知消息對象
 * @author oKong
 *
 */
@Document(collection="notify_msg")//集合名
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class NotifyMsg implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = -8985545025018238754L;

    @Id
    String id;
    
    /**
     * 消息類型
     */
    @Indexed
    String notifyType;
    
    /**
     * 消息單號
     */
    @Indexed
    String notifyNo;
    
    /**
     * 消息通知日期
     */
    String notifyDate;
    
    /**
     * 消息體
     */
    @Field("notifyMsg")//可指定存儲時的字段名
    String notifyMsg;
    
    /**
     * 建立時間
     */
    @CreatedDate
    Date gmtCreate;
}

這裏注意:@Document(collection="notify_msg") 表示:操做的集合爲:notify_msg。 這個可手動使用工具建立下。

另外,針對@CreatedDate註解,也和以前的jpa用法一直,建立時會自動賦值,須要在啓動類中添加@EnableMongoAuditing註解使其生效!

同時,可以使用@Field註解,可指定存儲的鍵值名稱,默認就是類字段名。如設置@Field("notify_Msg")後,效果以下:

@Field註解聲明鍵值

2.配置文件中填寫鏈接地址。

#mongodb
# 單機模式 mongodb://name:pass@ip:port/database
# 集羣模式 mongodb://user:pwd@ip1:port1,ip2:port2/database
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/learning

注意,這裏填寫格式

3.啓動類編寫。

/**
 * mongodb 集成示例
 * @author oKong
 *
 */
@SpringBootApplication
@EnableMongoAuditing
//@EnableMongoRepositories(basePackages="cn.lqdev")//當有些dao不在default page下時 可經過此方法進行註冊掃描包
@Slf4j
public class MongodbApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(MongodbApplication.class, args);
        log.info("spring-boot-mongodb-chapter31啓動!");
    }
}

注意:當使用MongoRepositories時,可能有些MongoRepositories類不在默認的包路徑(啓動類路徑)下,可以使用@EnableMongoRepositoriesbasePackages須要掃描的路徑信息。若都在默認的包路徑下,能夠不加此註解的。

MongoTemplate方式

如下示例下MongoTemplate方式進行數據操做。

0.建立一個接口類:

/**
 * 接口服務
 * @author oKong
 *
 */
public interface NotifyMsgService {

    /**
     * 保存數據
     * @author 做者:oKong
     */
    NotifyMsg saveNotifyMsg(NotifyMsg msg);
    
    /**
     * 根據消息號查找
     * @author 做者:oKong
     */
    NotifyMsg findNotifyMsgByNo(String notifyNo);
    
    /**
     * 根據消息日期查找
     * @author 做者:oKong
     */
    List<NotifyMsg> findNotifyMsgByDate(String notifyDate);
    
    /**
     * 根據id進行刪除 返回刪除的對象
     * @author 做者:oKong
     */
    NotifyMsg delNotifyMsgById(String id);
    
}

1.接口實現類,引入MongoTemplate

/**
 * MongoTemplate 訪問實現
 * @author oKong
 *
 */
@Service
public class NotifyMsgServiceImpl implements NotifyMsgService{

    @Autowired
    MongoTemplate mongoTemplate;
    
    @Override
    public NotifyMsg saveNotifyMsg(NotifyMsg msg) {
        //使用 save和insert均可以進行插入
        //區別:當存在"_id"時
        //insert 插入已經存在的id時 會異常
        //save 則會進行更新
        //簡單來講 save 就是不存在插入 存在更新
        mongoTemplate.insert(msg);
        mongoTemplate.save(msg);
        
        return msg;
    }

    @Override
    public NotifyMsg findNotifyMsgByNo(String notifyNo) {
        //根據Criteria 改造查詢條件
        Query query = new Query(Criteria.where("notifyNo").is(notifyNo));
        return mongoTemplate.findOne(query, NotifyMsg.class);
    }

    @Override
    public List<NotifyMsg> findNotifyMsgByDate(String notifyDate) {
        //查找 notifyDate 根據Criteria 改造查詢條件
        Query query = new Query(Criteria.where("notifyDate").is(notifyDate));        
        return mongoTemplate.find(query, NotifyMsg.class);
    }

    @Override
    public NotifyMsg delNotifyMsgById(String id) {
        //查找 id 根據Criteria 改造查詢條件
        Query query = new Query(Criteria.where("id").is(id));    
        return mongoTemplate.findAndRemove(query, NotifyMsg.class);
    }

}

針對查詢,可使用org.springframework.data.mongodb.core.query.Criteria對象進行構造查詢條件。其提供的方法以下:

Criteria

具體使用時,可根據實際狀況進行組合查詢條件。

針對saveinsert也須要注意下:

  • 在無_id狀況下,二者都能進行新增操做。
  • 存在_id,同時記錄庫裏不存在,二者都是進行插入操做。
  • 存在_id,同時庫裏也存在記錄save至關於進行更新操做。而insert直接就異常了。

2.建立示例控制層。

/**
 * mongoTemplate 示例
 * @author oKong
 *
 */
@RestController
@RequestMapping("/template")
@Slf4j
public class MongoTemplateController {

    @Autowired
    NotifyMsgService notifyMsgService;
    
    @PostMapping("/add")
    public NotifyMsg add(NotifyMsg msg) {
        log.info("mongoTemplate方式新增:{}", msg);
        return notifyMsgService.saveNotifyMsg(msg); 
    }
    
    @PostMapping("del/{id}")
    public NotifyMsg del(@PathVariable String id) {
        log.info("mongoTemplate方式刪除:{}", id);
        return notifyMsgService.delNotifyMsgById(id);
    }
    
    @GetMapping("/find/{no}")
    public NotifyMsg findNotifyMsgByNo(@PathVariable String no){
        log.info("mongoTemplate方式查找:notifyNo-{}", no);
        return notifyMsgService.findNotifyMsgByNo(no);
    }
    
    @GetMapping("/find/list/{date}")
    public List<NotifyMsg> findNotifyMsgByDate(@PathVariable String date){
        log.info("mongoTemplate方式查找:notifyDate-{}", date);
        return notifyMsgService.findNotifyMsgByDate(date);
    }
}

3.啓動應用,使用Postman進行訪問。

add

能夠看見,已經返回對應的信息,同時數據庫也可看見記錄了。

其餘的都是相似的,你們可自行訪問下:

MongoRepository方式

以上還須要本身編寫一些類啥的,如今是jpa的方式進行操做數據,優雅,簡單。

0.建立資源類

/**
 * MongoRepository 示例
 * @author oKong
 *
 */
public interface NotifyMsgDao extends MongoRepository<NotifyMsg, String>{

    /*
     * 根據消息號進行查詢
     */
    NotifyMsg findByNotifyNo(String notifyNo);
    
    /**
     * 根據日期查詢 自定義查詢
     * @author 做者:oKong
     */
    //須要注意 查詢的語法結構 ,同時這裏和`jpa`不同的地方是,第一個索引值從0 開始。。
    @Query("{'notifyDate':?0}")
    Page<NotifyMsg> queryBySql(String notifyDate,Pageable pageable);
}

這裏須要注意一個地方:和上一章節的自定義sql不一樣之處是,參數索引值從0開始。

query注意點

同時,要注意查詢的語法。具體用法,可查看:https://docs.spring.io/spring-data/mongodb/docs/1.10.14.RELEASE/reference/html/#mongodb.repositories.queries 這裏簡單截圖下:

1.編寫示例控制層。

/**
 * MongoRepository 示例
 * @author oKong
 *
 */
@RestController
@RequestMapping("/repository")
@Slf4j
public class MongoRepositoryController {

    @Autowired
    NotifyMsgDao notifyMsgDao;
    
    @PostMapping("/add")
    public NotifyMsg add(NotifyMsg msg) {
        log.info("repository方式新增:{}", msg);
        return notifyMsgDao.save(msg);
    }
    
    @GetMapping("/find/sql/{date}")
    public Page<NotifyMsg> queryBySql(@PathVariable String date){
        Pageable pageable = new PageRequest(0, 10);
        log.info("repository方式分頁sql查找日期:{}", date);
        return notifyMsgDao.queryBySql(date, pageable);
    }
    
    @GetMapping("/find/{no}")
    public NotifyMsg findByNotifyNo(@PathVariable String no) {
        log.info("repository方式查找單號:{}", no);
        return notifyMsgDao.findByNotifyNo(no);
    }
    
}

2.啓動應用,使用Postman,訪問具體的方法,就能夠看見相關結果了。

也可直接利用可視化工具,直接查看數據信息

工具查看

參考資料

  1. https://docs.spring.io/spring-data/mongodb/docs/1.10.14.RELEASE/reference/html

  2. https://docs.spring.io/spring-boot/docs/1.5.15.RELEASE/reference/htmlsingle/#boot-features-mongodb

  3. https://www.mongodb.com/cn

  4. http://www.ityouknow.com/springboot/2017/05/08/springboot-mongodb.html

總結

本章節主要介紹了Mongodb的集成和簡單的使用。相關更加詳細的用法,可取官網查閱下,若使用MongoRepository模式,基本和上章節講的Spring-data-jpa用法差很少,有些細微差異,就是自定義查詢sql上了,畢竟一個是關係型數據庫,一個是NoSql數據庫,查詢的語法還有略有不一樣的。而使用MongoRepository仍是MongoTemplate,就看我的喜愛了。自從接觸了jpa後,是傾向於前者的,畢竟真的比較簡單呀!想多複雜用法的你們自定查閱官網信息吧。

最後

目前互聯網上不少大佬都有SpringBoot系列教程,若有雷同,請多多包涵了。原創不易,碼字不易,還但願你們多多支持。若文中有所錯誤之處,還望提出,謝謝。

老生常談

  • 我的QQ:499452441
  • 微信公衆號:lqdevOps

公衆號

我的博客:http://blog.lqdev.cn

完整示例:https://github.com/xie19900123/spring-boot-learning/tree/master/chapter-31

原文地址:http://blog.lqdev.cn/2018/11/01/springboot/chapter-thirty-one/

相關文章
相關標籤/搜索