構(gòu)建RESTful服務(wù)(使用SpringDataJPA)-創(chuàng)新互聯(lián)

一.Restful簡介
REST是一種Web軟件結(jié)構(gòu)風(fēng)格,而不是一種標(biāo)準(zhǔn),匹配或兼容這種架構(gòu)風(fēng)格稱之為REST服務(wù),REST服務(wù)簡潔并且有層次,REST通常基于HTTP,URI和XML以及HTML這些現(xiàn)有的廣泛流行的協(xié)議和標(biāo)準(zhǔn),在REST中,資源是由URI來指定的,對資源的增刪改查也是通過HTTP協(xié)議提供的POST,PUT,GET,DELETE等方法實(shí)現(xiàn),使用REST可以更高效率的利用緩存來提高響應(yīng)速度,同時REST中的通信會話狀態(tài)有客戶端來維護(hù),這可以讓不同服務(wù)器來處理一系列請求中的不同請求,進(jìn)而提高服務(wù)器的擴(kuò)展性,在前后端分離項(xiàng)目中,一個好的項(xiàng)目必然遵循REST架構(gòu)風(fēng)格
在Spring Mvc框架中,開發(fā)者可以提供RestController注解開發(fā)一個RESTful服務(wù),不過Spring Boot對此提供了自動化配置方案,開發(fā)者只需要添加相關(guān)依賴即可快速構(gòu)建一個RESTful服務(wù)
二.JPA實(shí)現(xiàn)REST
在Spring Boot中使用Spring Data JPA和Spring Data Rest可以快速開發(fā)一個RESTful服務(wù)。
1.基本實(shí)現(xiàn)
(1)創(chuàng)建項(xiàng)目:創(chuàng)建Spring Boot項(xiàng)目,添加如下依賴

創(chuàng)新互聯(lián)公司專注于中大型企業(yè)的網(wǎng)站建設(shè)、網(wǎng)站設(shè)計和網(wǎng)站改版、網(wǎng)站營銷服務(wù),追求商業(yè)策劃與數(shù)據(jù)分析、創(chuàng)意藝術(shù)與技術(shù)開發(fā)的融合,累計客戶1000+,服務(wù)滿意度達(dá)97%。幫助廣大客戶順利對接上互聯(lián)網(wǎng)浪潮,準(zhǔn)確優(yōu)選出符合自己需要的互聯(lián)網(wǎng)運(yùn)用,我們將一直專注高端網(wǎng)站設(shè)計和互聯(lián)網(wǎng)程序開發(fā),在前進(jìn)的路上,與客戶一起成長!
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
         <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

(2)這里的依賴除了添加了數(shù)據(jù)庫相關(guān)依賴外還有Spring Data Jpa以及Spring Data Rest的依賴,項(xiàng)目建成后,接下來在配置文件中進(jìn)行配置,配置如下:

server.port=8088

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/spring_vue?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=********

spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.open-in-view=true
spring.jpa.properties.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

2.創(chuàng)建實(shí)體類

@Entity
@Data
@Table(name = "book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

    @Column(name = "author")
    private String author;

    @Column(name = "price")
    private float price;

}

3.創(chuàng)建BookRepository

public interface BookRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor{

}

(3)這里繼承了JpaRepository,JpaSpecificationExecutor,在JpaRepository中包含了很多現(xiàn)成的增刪改查的方法
4.測試
經(jīng)過上面的步驟,簡單的RESTful架構(gòu)就已經(jīng)完成了,接下來進(jìn)行測試:
(1)添加測試,這里我們使用的Postman,RESTful構(gòu)建成功后,默認(rèn)的請求路徑是實(shí)體類名小名加上s,向數(shù)據(jù)庫添加一條數(shù)據(jù)很容易,發(fā)起一個post請求,并寫入要添加的數(shù)據(jù)即可,這里數(shù)據(jù)以JSON格式為準(zhǔn),如下:

構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

總結(jié):路徑:localhost:8088/books,格式:JSON,請求類型:post
(2)分頁查詢測試,查詢是Get請求,分頁查詢請求路徑實(shí)體類小寫加s,這里為/books,分頁查詢的每頁默認(rèn)記錄數(shù)為20條,頁數(shù)是0,測試如下:

構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

總結(jié):請求類型GET,無參數(shù),路徑:localhost:8088/books
(3)根據(jù)id查詢,若是根據(jù)id進(jìn)行查詢,只需要路徑后邊綴id即可,路徑如下:

構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

總結(jié):路徑:localhost:8088/books/4,類型:GET
(4)分頁查詢擴(kuò)展,添加查詢頁數(shù),條數(shù),以及添加排序,也是只需要后綴參數(shù)即可
構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

總結(jié):路徑:localhost:8088/books?page=1&size=3,請求類型:GET
除了分頁以外還可以添加排序,如下:

構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

總結(jié):路徑:localhost:8088/books?page=1&size=3&sort=id,desc,類型:GET
(5)修改測試,修改需要發(fā)送PUT請求,因?yàn)樾薷氖歉鶕?jù)id進(jìn)行的,因此路徑中需加入id,然后傳入修改數(shù)據(jù)(JSON格式),如下:
構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

總結(jié):路徑:localhost:8088/books/15,請求參數(shù)圖中所示,請求類型:PUT
(6)刪除測試,使用DELETE請求可以實(shí)現(xiàn)對數(shù)據(jù)的刪除操作,例如刪除id為1的記錄,路由如下:localhost:8088/books/11
5.自定義請求路徑
默認(rèn)情況下,請求路徑都是實(shí)體類名加s,如果開發(fā)者想對路徑進(jìn)行重定義,通過@RepositoryResource注解可實(shí)現(xiàn)

@RepositoryRestResource(path="bs",collectionResourceRel="bs",itemResourceRel="bs")
public interface BookRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor{

}

代碼解釋:@RepositoryResource注解的path屬性表示將所有請求路徑中的books都修改為bs(localhost:8088/bs),collectionResourceRel表示將返回的JSON集合中book集合的key修改為bs,itemResourceRel表示將返回的JSON集合中單個book的key修改為b

構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

6.自定義查詢方法
默認(rèn)的查詢方法支持分頁查詢,排序查詢以及按照id查詢,如果開發(fā)者想要按照某個屬性查詢,只需要在BookRepository中定義相關(guān)方法并暴露出去即可,代碼如下:

@RepositoryRestResource(path = "bs")
public interface BookRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor {
    @RestResource(path = "author", rel = "author")
    public List<Book> findByAuthor(@Param("author") String author);
}

代碼解釋:
自定義查詢只需要在BookRepository中定義查詢方法即可,方法定義好之后可以不添加@RestResource注解,默認(rèn)路徑就是方法名,以上述自定義方法為例,若是不添加@RestResource注解,則默認(rèn)該方法調(diào)用路徑為:localhost:8088/bs/search/findByAuthor?author=金庸,如果添加注解,對方法查詢路徑自定義,其中path就是最新路徑,如上方法,他的訪問路徑為:localhost:8088/bs/search//author?author=金庸 ,如下:

構(gòu)建RESTful服務(wù)(使用Spring Data JPA)

注意:用戶可以通過訪問:localhost:8088/bs/search,查詢目前都暴露了哪些查詢方法

7.隱藏方法
(1)默認(rèn)情況下,繼承了Repository接口或是其子類的類都會被暴露出來,即開發(fā)者可以執(zhí)行基本的增刪改查方法,如果開發(fā)者不想暴露此接口類對對象的操作各種方法,那么就可以作如下配置:

@RepositoryRestResource(exported=false)
public interface BookRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor {
}

這樣此接口里邊的所有方法都會失效
(2)若是只是不想暴露某一個方法,就可以在此方法上加注解@RestResource,在注解中設(shè)定exported=false,這樣這個方法就會失效,如下:

@Override
    @RestResource(exported=false)
    void deleteById(Integer id);

8.配置CORS(跨域支持)
所有方法支持跨域訪問,在接口上加@CrossOrigin注解如下:

@CrossOrigin
@RepositoryRestResource(path = "bs")
public interface BookRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor {
    @RestResource(path = "author", rel = "author")
    public List<Book> findByAuthor(@Param("author") String author);

}

(2)單某些方法支持跨域,在要支持的方法上加@CrossOrigin注解
9.其他配置
開發(fā)者可以為了方便開發(fā)添加常用屬性,如下:

spring.data.rest.default-page-size=2
spring.data.rest.page-param-name=path
spring.data.rest.sort-param-name=sort
spring.data.rest.limit-param-name=size
spring.data.rest.base-path=/api
spring.data.rest.return-body-on-create=true
spring.data.rest.return-body-on-update=true

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

文章標(biāo)題:構(gòu)建RESTful服務(wù)(使用SpringDataJPA)-創(chuàng)新互聯(lián)
本文路徑:http://bm7419.com/article2/ihpoc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作外貿(mào)建站、手機(jī)網(wǎng)站建設(shè)網(wǎng)站設(shè)計公司、云服務(wù)器、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作