1. 程式人生 > >SpringBoot 之分頁查詢

SpringBoot 之分頁查詢

前言

學習資料庫很久了,並且對於CRUD(增、刪、改、查)已經爛熟於心了,相信許多跟我一樣還天天對於資料庫的操作僅限於此的朋友們一定早已感到枯燥了,那麼我們趕緊進入話題,來談談分頁查詢的使用吧!
(基本上是第一次寫部落格,有錯的或是言語不當的地方還望多多指教,在此跪拜了)

什麼是分頁查詢

分頁查詢,就是將過多的結果再有限的頁面上分好多頁來顯示,這是許多網站常用的功能,也是最基本的功能。

分頁查詢的應用

這裡我們使用的是 SpringBoot 中 JPA 的分頁查詢

首先引入JPA的依賴

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

Repository層

import com.Model.UserInfo;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface SourceCodeDao extends PagingAndSortingRepository<UserInfo, Integer> {
}

該介面繼承了PagingAndSortingRepository中的方法

Service層

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import com.Model.UserInfo;
import com.Repository.SourceCodeDao;

public Page<UserInfo> getSourceCode(int pageNumber, int pageSize){
        PageRequest request = this
.buildPageRequest(pageNumber,pageSize); Page<UserInfo> sourceCodes = this.sourceCodeDao.findAll(request); return sourceCodes; } private PageRequest buildPageRequest(int pageNumber, int pagzSize) { return new PageRequest(pageNumber - 1, pagzSize, null); }

getSourceCode()方法傳入兩個引數,pageNumber為頁碼的當前頁,pageSize為每一頁顯示的條數,該方法返回值為一個Page型別(UserInfo是每條資訊對應的實體類)

PageRequest()中傳入三個引數,前兩個參照上面,注意第一個引數需要減一,因為分頁的當前頁是從0開始算起,最後一個引數為排序屬性,可以設定為按照自己想要的方式進行排序,因為我這裡分頁查出來後的資料不涉及到排序,所以這裡排序我直接傳入null。

Controller層

import org.springframework.data.domain.Page;
import net.sf.json.JSONArray;

Page<UserInfo> sourceCodes = this.sourceCodeService.getSourceCode(pageNow, rows);
JSONArray jsonArray = JSONArray.fromObject(sourceCodes.getContent().toArray());

我最後的分頁結果我轉換成了JsonArray格式傳給了前臺,然後前臺遍歷顯示在頁面上

總結

這次因為專案中需要使用分頁,於是百度查詢了下分頁的使用,成功執行後在此簡單的記錄下也希望能幫到更多的人。