MyBatis分頁插件

什麼是MyBatis分頁插件?

平時寫代碼我們可以自己封裝一個分頁類,從而使用mysql的limit來進行,這種方法我就不多說了。MyBatis分頁插件就是PageHelper,目前支持常見的 12 種數據庫,Oracle,MySq,SqlServer 等。是一種物理分頁插件並且遵循QueryInterceptor 規範。

添加Maven依賴

我們首先添加依賴,我這裏就用mysql演示,大家根據自己實際情況添加依賴

        <!--MyBatis分頁插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
      
       <!--Mysql數據庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

在mybatis-config.xml開啓分頁插件的代碼

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
        </plugin>
    </plugins>
</configuration>

在application.yml中配置,也可以使用@Bean注入的方式

pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

配置說明

1. helperDialect:分頁插件會自動檢測當前的數據庫鏈接,自動選擇合適的分頁方式。 你可以配置helperDialect屬性來指定分頁插件使用哪種方言。

2. reasonable:分頁合理化參數,默認值爲false。當該參數設置爲 true 時,pageNum<=0 時會查詢第一頁,pageNum>pages(超過總數時),會查詢最後一頁。默認false 時,直接根據參數進行查詢。

3.supportMethodsArguments:支持通過 Mapper 接口參數來傳遞分頁參數,默認值false,分頁插件會從查詢方法的參數值中,自動根據上面 params 配置的字段中取值,查找到合適的值時就會自動分頁。 使用方法可以參考測試代碼中的 com.github.pagehelper.test.basic 包下的 ArgumentsMapTest 和 ArgumentsObjTest。

4.params:爲了支持startPage(Object params)方法,增加了該參數來配置參數映射,用於從對象中根據屬性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值, 默認值爲pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero。

而後創建實體類,mapper,service並且在controller中返回一個List集合

    @RequestMapping("/sel.list")
    @ResponseBody
    public List<PmsBrand> list(){
        PageHelper.startPage(1, 5);
        List<PmsBrand> infos=pmsBrandService.findAll();
        return infos;
    }

最好運行項目測試

完成效果

在這裏插入圖片描述

學習文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章