第五十二章:基於SpringBoot2使用Rest訪問MongoDB數據

在以前項目中咱們想要讀取MongoDB內的內容須要使用MongoDBTemplate來完成數據的CRUD,那若是咱們想要經過RestController的形式獲取MongoDB內的數據就更麻煩了,還須要自行去建立對應的控制器,而後使用MongoDBTemplateMongoDB內讀取出數據後返回給前端。前端

在上一章節第五十一章:基於SpringBoot2 & MongoDB完成自動化集成咱們講到了SpringBoot2MongoDB集成後怎麼簡單的操做數據,固然Spring Data Xxx家族方式的設計與Spring Data JPA同樣,Sring Data MongoDB提供了一個MongoRepository<T,PK>接口來爲繼承該接口的子接口自動提供代理類完成數據操做實現。git


本章目標

使用Spring Data Rest自動映射讀取MongoDB內的數據,省去一系列繁瑣的操做步驟。redis

爲你推薦

  1. 第五十一章:基於SpringBoot2 & MongoDB完成自動化集成
  2. 第五十章:SpringBoot2.0新特性 - 豈止至今最簡單redis緩存集成
  3. 第四十九章:SpringBoot2.0新特性 - 你get到WebMvcConfigurer兩種配置方式了嗎?
  4. 第四十八章:SpringBoot2.0新特性 - RabbitMQ信任package設置
  5. 第四十七章:SpringBoot2.0新特性 - Quartz自動化配置集成

SpringBoot 企業級核心技術學習專題


專題 專題名稱 專題描述
001 Spring Boot 核心技術 講解SpringBoot一些企業級層面的核心組件
002 Spring Boot 核心技術章節源碼 Spring Boot 核心技術簡書每一篇文章碼雲對應源碼
003 Spring Cloud 核心技術 對Spring Cloud核心技術全面講解
004 Spring Cloud 核心技術章節源碼 Spring Cloud 核心技術簡書每一篇文章對應源碼
005 QueryDSL 核心技術 全面講解QueryDSL核心技術以及基於SpringBoot整合SpringDataJPA
006 SpringDataJPA 核心技術 全面講解SpringDataJPA核心技術
007 SpringBoot核心技術學習目錄 SpringBoot系統的學習目錄,敬請關注點贊!!!

構建項目

使用Idea開發工具建立一個SpringBoot的項目,添加相應的依賴,pom.xml配置文件依賴內容以下所示:spring

<dependencies>
        <!--mongodb依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <!--data rest依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--Lombok依賴-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
複製代碼

咱們本章節的依賴比上一章多了一個spring-boot-starter-data-rest,經過這個依賴咱們能夠自動完成RestController的依賴配置,不須要再手動去建立控制器,由於咱們經過一些簡單的註解配置以及固定格式名稱規則的方法就能夠完成控制器的實現。mongodb

由於本章的內容須要在上一章的基礎上編寫,因此咱們直接把以前章節的相關的配置以及類都複製到本項目內,複製的內容有:application.ymlCustomerCustomerRepository。(源碼位置:第五十一章源碼)瀏覽器


改造CustomerRepository

spring-boot-starter-data-rest會自動掃描添加@RepositoryRestResource註解的接口,自動將該接口映射爲一系列可經過rest訪問的請求路徑,這裏說到一系列,咱們在測試的時候會講到爲何說是一系列!!!。 既然須要添加註解,那麼咱們就打開CustomerRepository接口,對應爲它添加上以下註解內容:緩存

@RepositoryRestResource(collectionResourceRel = "customer", path = "customer")
public interface CustomerRepository extends MongoRepository<Customer, String> {
//....省略
}
複製代碼

註解內須要提供兩個參數, collectionResourceRel:該參數配置映射MongoDB內的Collection名稱。 path:該參數配置映射完成rest後訪問的路徑前綴。bash


運行測試

咱們先來簡單的運行測試下是否能夠經過咱們配置的path路徑實現訪問內容,啓動項目時咱們能夠看到控制檯的輸出內容:微信

Mapped "{[/{repository}/search],methods=[GET] Mapped "{[/{repository}/search/{search}],methods=[GET]
Mapped "{[/{repository}/{id}/{property}],methods=[GET] Mapped "{[/{repository}],methods=[GET]
....
複製代碼

咱們配置一個@RepositoryRestResource註解的接口就會根據rest內置的一系列的條件生成對應的請求,這也是咱們在以前說到的一系列請求路徑的地方,咱們先來訪問下映射/{repository}的路徑。app


測試 /{repository} 映射路徑

你若是使用Windows系統直接打開瀏覽器輸出地址就能夠看到返回的內容,若是你使用Linux或者OS X系統能夠在Terminal使用curl命令查看返回內容。

咱們訪問:http://localhost:8080/customer,路徑查看返回的內容:

➜  ~ curl http://localhost:8080/customer
{
  "_embedded" : {
    "customer" : [ {
      "firstName" : "恆宇",
      "lastName" : "少年",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/customer/5adbec9ceb89f105acd90cec"
        },
        "customer" : {
          "href" : "http://localhost:8080/customer/5adbec9ceb89f105acd90cec"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/customer{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/customer"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}
複製代碼

經過這個地址咱們能夠讀取出@RepositoryRestResource註解配置的collectionResourceRel對應的 MongoDB.collection集合內的數據,咱們發現不只讀取出來了數據並且還爲咱們提供了分頁的信息,這但是很貼心的地方啊,默認讀取第1頁每頁20條數據。


測試 /{repository}/{id} 映射路徑

咱們訪問http://localhost:8080/customer/5adbec9ceb89f105acd90cec(注意:這裏的id是你本地生成的,這個id是我本地生成,直接訪問會出現404)以下所示:

➜  ~ curl http://localhost:8080/customer/5adbec9ceb89f105acd90cec
{
  "firstName" : "恆宇",
  "lastName" : "少年",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/customer/5adbec9ceb89f105acd90cec"
    },
    "customer" : {
      "href" : "http://localhost:8080/customer/5adbec9ceb89f105acd90cec"
    }
  }
}
複製代碼

根據返回的內容看到是可以訪問根據id查詢的數據內容的。


測試 /{repository}/search/{search} 映射路徑

這個映射的配置是專門爲咱們自定義方法準備的,自定義方法的規則與SpringDataJPA的方法名稱規則同樣,當咱們在接口建立findByXxx方法時Idea會自動爲咱們提示相應的內容,下面咱們就建立兩個不一樣的查詢方法,以下所示:

/**
     * 更加名字查詢數據
     *
     * @param firstName 名字
     * @return
     */
    List<Customer> findByFirstName(@Param("firstName") String firstName);

    /**
     * 根據姓氏查詢出最靠前的一條數據
     *
     * @param lastName 姓氏
     * @return
     */
    Customer findTopByLastName(@Param("lastName") String lastName);
複製代碼

下面咱們重啓下項目訪問路徑http://localhost:8080/customer/search/findByFirstName?firstName=恆宇能夠看到返回內容:

➜  ~ curl http://localhost:8080/customer/search/findByFirstName\?firstName\=%E6%81%92%E5%AE%87
{
  "_embedded" : {
    "customer" : [ {
      "firstName" : "恆宇",
      "lastName" : "少年",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/customer/5adbec9ceb89f105acd90cec"
        },
        "customer" : {
          "href" : "http://localhost:8080/customer/5adbec9ceb89f105acd90cec"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/customer/search/findByFirstName?firstName=%E6%81%92%E5%AE%87"
    }
  }
}
複製代碼

自動的根據咱們的配置的方法查詢出了對應的數據,自動過濾了對應的數據,不過這個是沒有分頁的。 一樣另一個自定義方法的請求http://localhost:8080/customer/search/findTopByLastName?lastName=少年,也是同樣的能夠對應的獲取過濾後的數據。

注意:@Param註解內的參數名稱要與Customer內的屬性對應。

若是你想查看配置的所有自定義的方法,訪問:http://localhost:8080/customer/search,以下所示:

➜  ~ curl http://localhost:8080/customer/search                                               
{
  "_links" : {
    "findByFirstName" : {
      "href" : "http://localhost:8080/customer/search/findByFirstName{?firstName}",
      "templated" : true
    },
    "findTopByLastName" : {
      "href" : "http://localhost:8080/customer/search/findTopByLastName{?lastName}",
      "templated" : true
    },
    "self" : {
      "href" : "http://localhost:8080/customer/search"
    }
  }
}
複製代碼

總結

本章內容主要是圍繞着spring-boot-starter-data-rest這個依賴進行的,這個依賴幫助咱們完成了平常編碼中一些重複的工做,並且很智能的提供了一些映射,更方便咱們進行查詢數據。

本章源碼已經上傳到碼雲: SpringBoot配套源碼地址:gitee.com/hengboy/spr… SpringCloud配套源碼地址:gitee.com/hengboy/spr… SpringBoot相關係列文章請訪問:目錄:SpringBoot學習目錄 QueryDSL相關係列文章請訪問:QueryDSL通用查詢框架學習目錄 SpringDataJPA相關係列文章請訪問:目錄:SpringDataJPA學習目錄,感謝閱讀! 歡迎加入QQ技術交流羣,共同進步。

QQ技術交流羣1
更新資源分享掃碼關注微信公衆號:
掃碼關注 - 專一分享
相關文章
相關標籤/搜索