1. 程式人生 > >微專案:一步一步帶你使用SpringBoot入門(二)

微專案:一步一步帶你使用SpringBoot入門(二)

今天我們來使用JPA做分頁專案並且做講解

如果是新來的朋友請回上一篇
上一篇:微專案(一)

maven整合

在pom檔案的dependencies依賴中匯入以下依賴

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

然後重啟專案

我們可以看到專案跑起來後執行出來一個tomcat

我們可以看到這裡出現了404錯誤。雖然是錯誤但是出來這個就對了。

下面我們來配置對專案的增和查

在做增查之前,我們需要新建倆個包。

下面我們逐一填東西。

service

service是邏輯層,包括資料處理的方向,和過程。

這裡第一個方法好理解,就是向資料庫內新增文章。

第二個方法查代表的含義是將資料庫分頁,

為什麼這麼做呢?很簡單,如果資料過多無法展示我們只能這麼做。按照ID倒序排列。

package cn.baldorange.anonymous.service;

import cn.baldorange.anonymous.entity.Wall;
import cn.baldorange.anonymous.repository.WallRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class WallService {
    @Autowired
    WallRepo wallRepo;

    /**
     * 增加吐槽
     * @param title
     * @param content
     * @return
     */
    public Boolean saveNewWall(String title,String content){
        try {
            String summary = "";
            if (content.length() > 100)
                summary = content.substring(0, 99);
            else summary = content;
            Wall wall = new Wall(title, content, new Date(), summary, "0");
            wallRepo.save(wall);
            return true;
        }catch (Exception e){
            return false;
        }
    }



    /**
     * 獲得匿名牆的所有文章
     * @return
     */
    public Page<Wall> findAllWalls(Integer page,Integer size){
        if(page == null) page = 0;
        if(size == null) size =10;
        PageRequest pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");
        return wallRepo.findAll(pageable);
    }
}

controller

至於Controller層就比較簡單了,

但是從servlet過來的同學要注意了,@PutMapping這裡可能會給你們帶來疑惑,實際上現在http請求常用的不僅僅是get和post 還有 put delete 等等我們沒見過的,規定是人定的,人也能改。

package cn.baldorange.anonymous.controller;

import cn.baldorange.anonymous.entity.Wall;
import cn.baldorange.anonymous.service.WallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/walls")
public class Controller {
    @Autowired
    WallService wallService;

    @PutMapping("/saveNewWall")
    public Boolean saveNewWall(@RequestParam String title,@RequestParam String content){
        return wallService.saveNewWall(title,content);
    }


    @GetMapping("/findAllWalls")
    public Page<Wall> findAllWalls(Integer page, Integer size){
        return wallService.findAllWalls(page,size);
    }

}

配置好後我們啟動後訪問這裡:
http://127.0.0.1:8080/walls/findAllWalls

這就是我們所見到的json資料

雖然很亂,但是我們不難發現這裡面有我們資料庫中的內容。還有一些其他的東西。

我們下面就需要配置介面檔案了。

swagger

相信無論是前端還是後端開發,都或多或少地被介面文件折磨過。前端經常抱怨後端給的介面文件與實際情況不一致。後端又覺得編寫及維護介面文件會耗費不少精力,經常來不及更新。其實無論是前端呼叫後端,還是後端呼叫後端,都期望有一個好的介面文件。但是這個介面文件對於程式設計師來說,就跟註釋一樣,經常會抱怨別人寫的程式碼沒有寫註釋,然而自己寫起程式碼起來,最討厭的,也是寫註釋。所以僅僅只通過強制來規範大家是不夠的,隨著時間推移,版本迭代,介面文件往往很容易就跟不上程式碼了。

首先將maven中引入swagger

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

然後我們新建個包最終目錄如下:

swaggerConfig配置檔案如下:

package cn.baldorange.anonymous.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class swaggerConfig {
    @Bean
    Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder().description("專案").build());
    }
}

OK我們現在重啟專案:
並訪問這裡

OK我們現在可以使用swagger進行介面測試了,炒雞棒。

分頁技術

資料庫分頁也是在資料庫裡寫查詢語句,不同的是查詢的都是指定條數到指定條數的資料,不是一次性把資料全查出來。

當size=2時,返回如下

當size=2,page=2時,返回如下

當size或者page越界時,返回如下

這裡的分頁後的欄位描述如下:

{
    "content": [{}], // 資料列表
    "last": true, // 是否最後一頁
    "totalPages": 1, // 總頁數
    "totalElements": 1, // 資料總數
    "sort": null, // 排序
    "first": true, // 是否首頁
    "numberOfElements": 1, // 本頁資料條數
    "size": 10, // 每頁長度
    "number": 0 // 當前頁序號
}

不難看出,JPA的分頁機制特別好用,簡直不要太爽。

git推上去

OK今天的活就完工了