Mybatis 分頁:Pagehelper + 攔截器實現

風塵部落格發表於2020-05-12

一、分頁外掛 Pagehelper

PageHelperMybatis的一個分頁外掛,非常好用!

1.1 Spring Boot 依賴

<!-- pagehelper 分頁外掛-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.12</version>
</dependency>

也可以這麼引入

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>latest version</version>
</dependency>

1.2 PageHelper 配置

配置檔案增加PageHelper的配置,主要設定了分頁方言和支援介面引數傳遞分頁引數,如下:

pagehelper:
  # 指定資料庫
  helper-dialect: mysql
  # 預設是false。啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages(最大頁數)會查詢最後一頁。禁用合理化時,如果pageNum<1或pageNum>pages會返回空資料
  reasonable: false
  # 是否支援介面引數來傳遞分頁引數,預設false
  support-methods-arguments: true
  # 為了支援startPage(Object params)方法,增加了該引數來配置引數對映,用於從物件中根據屬性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置對映的用預設值, 預設值為pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero
  params: count=countSql
  row-bounds-with-count: true

專案完整配置檔案詳見文mybatis-pagehelper

1.3 如何分頁

只有緊跟在PageHelper.startPage方法後的第一個Mybatis的查詢(Select)方法會自動分頁!!!!

@Test
public void selectForPage() {
    // 第幾頁
    int currentPage = 2;
    // 每頁數量
    int pageSize = 5;
    // 排序
    String orderBy = "id desc";
    PageHelper.startPage(currentPage, pageSize, orderBy);
    List<UserInfoPagehelperDO> users = userInfoPagehelperMapper.selectList();
    PageInfo<UserInfoPagehelperDO> userPageInfo = new PageInfo<>(users);
    log.info("userPageInfo:{}", userPageInfo);
}
...: userPageInfo:PageInfo{pageNum=2, pageSize=5, size=1, startRow=6, endRow=6, total=6, pages=2, list=Page{count=true, pageNum=2, pageSize=5, startRow=5, endRow=10, total=6, pages=2, reasonable=false, pageSizeZero=false}[UserInfoPagehelperDO{id=1, userName='null', age=22, createTime=null}], prePage=1, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true, hasNextPage=false, navigatePages=8, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}

這裡的返回結果包括資料、是否為第一頁/最後一頁、總頁數、總記錄數,詳見Mybatis-PageHelper

Pagehelper 分頁完整示例

二、Mybatis 攔截器實現分頁

2.1 Mybatis 攔截器

Mybatis 官網【外掛】部分有以下描述:

  1. 通過 MyBatis 提供的強大機制,使用外掛是非常簡單的,只需實現 Interceptor 介面,並指定想要攔截的方法簽名即可。
  2. MyBatis 允許你在已對映語句執行過程中的某一點進行攔截呼叫。預設情況下,MyBatis 允許使用外掛來攔截的方法呼叫包括:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)

即:我們可以通過攔截器的方式,實現MyBatis外掛(資料分頁)

接下來重點演示我如何使用了攔截器實現分頁。

2.2 呼叫形式

在看如何實現之前,我們先看看如何使用:

照抄 PageHelper 的設計,先呼叫一個靜態方法,對下面第一個方法的sql語句進行攔截,在new一個分頁物件時自動處理。

@Test
public void selectForPage() {
    // 該查詢進行分頁,指定第幾頁和每頁數量
    PageInterceptor.startPage(1,2);
    List<UserInfoDO> all = dao.findAll();
    PageResult<UserInfoDO> result = new PageResult<>(all);
    // 分頁結果列印
    System.out.println("總記錄數:" + result.getTotal());
    System.out.println(result.getData().toString());
}

然後我們主要看看實現步驟。

2.3 資料庫方言

定義好一個方言介面,不同的資料使用不同的方言實現

  • Dialect.java
public interface Dialect {
    /**
     * 獲取count SQL語句
     *
     * @param targetSql
     * @return
     */
    default String getCountSql(String targetSql) {
        return String.format("select count(1) from (%s) tmp_count", targetSql);
    }

    /**
     * 獲取limit SQL語句
     * @param targetSql
     * @param offset
     * @param limit
     * @return
     */
    String getLimitSql(String targetSql, int offset, int limit);
}
  • Mysql 分頁方言
@Component
public class MysqlDialect implements Dialect{

    private static final String PATTERN = "%s limit %s, %s";

    private static final String PATTERN_FIRST = "%s limit %s";

    @Override
    public String getLimitSql(String targetSql, int offset, int limit) {
        if (offset == 0) {
            return String.format(PATTERN_FIRST, targetSql, limit);
        }

        return String.format(PATTERN, targetSql, offset, limit);
    }
}

2.4 攔截器核心邏輯

該部分完整程式碼見 PageInterceptor.java

  • 分頁輔助引數內部類 PageParam.java
public static class PageParam {
    // 當前頁
    int pageNum;

    // 分頁開始位置
    int offset;

    // 分頁數量
    int limit;

    // 總數
    public int totalSize;

    // 總頁數
    public int totalPage;
}
  • 查詢總記錄數
private long queryTotal(MappedStatement mappedStatement, BoundSql boundSql) throws SQLException {

    Connection connection = null;
    PreparedStatement countStmt = null;
    ResultSet rs = null;
    try {

        connection = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();

        String countSql = this.dialect.getCountSql(boundSql.getSql());

        countStmt = connection.prepareStatement(countSql);
        BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql,
                boundSql.getParameterMappings(), boundSql.getParameterObject());

        setParameters(countStmt, mappedStatement, countBoundSql, boundSql.getParameterObject());

        rs = countStmt.executeQuery();
        long totalCount = 0;
        if (rs.next()) {
            totalCount = rs.getLong(1);
        }

        return totalCount;
    } catch (SQLException e) {
        log.error("查詢總記錄數出錯", e);
        throw e;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("exception happens when doing: ResultSet.close()", e);
            }
        }

        if (countStmt != null) {
            try {
                countStmt.close();
            } catch (SQLException e) {
                log.error("exception happens when doing: PreparedStatement.close()", e);
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("exception happens when doing: Connection.close()", e);
            }
        }
    }
}
  • 對分頁SQL引數?設值
private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
                               Object parameterObject) throws SQLException {
    ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
    parameterHandler.setParameters(ps);
}
  • 利用方言介面替換原始的SQL語句
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());

    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
        StringBuffer keyProperties = new StringBuffer();
        for (String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }

    //setStatementTimeout()
    builder.timeout(ms.getTimeout());

    //setStatementResultMap()
    builder.parameterMap(ms.getParameterMap());

    //setStatementResultMap()
    builder.resultMaps(ms.getResultMaps());
    builder.resultSetType(ms.getResultSetType());

    //setStatementCache()
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());

    return builder.build();
}
  • 計算總頁數
public int countPage(int totalSize, int offset) {
    int totalPageTemp = totalSize / offset;
    int plus = (totalSize % offset) == 0 ? 0 : 1;
    totalPageTemp = totalPageTemp + plus;
    if (totalPageTemp <= 0) {
        totalPageTemp = 1;
    }
    return totalPageTemp;
}
  • 供呼叫的靜態分頁方法

我這裡設計的,頁數是從1開始的,如果習慣用0開始,可以自己修改。

public static void startPage(int pageNum, int pageSize) {
    int offset = (pageNum-1) * pageSize;
    int limit = pageSize;
    PageInterceptor.PageParam pageParam = new PageInterceptor.PageParam();
    pageParam.offset = offset;
    pageParam.limit = limit;
    pageParam.pageNum = pageNum;
    PARAM_THREAD_LOCAL.set(pageParam);
}

2.5 分頁結果集

為了便於結果封裝,我這裡自己封裝了一個比較全的分頁結果集,包含太多的東西了,自己慢慢看下面的屬性吧(自認為比較全了,歡迎打臉)

public class PageResult<T> implements Serializable {
    /**
     * 是否為第一頁
     */
    private Boolean isFirstPage = false;
    /**
     * 是否為最後一頁
     */
    private Boolean isLastPage = false;
    /**
     * 當前頁
     */
    private Integer pageNum;
    /**
     * 每頁的數量
     */
    private Integer pageSize;
    /**
     * 總記錄數
     */
    private Integer totalSize;
    /**
     * 總頁數
     */
    private Integer totalPage;
    /**
     * 結果集
     */
    private List<T> data;

    public PageResult() {
    }

    public PageResult(List<T> data) {
        this.data = data;
        PageInterceptor.PageParam pageParam = PageInterceptor.PARAM_THREAD_LOCAL.get();
        if (pageParam != null) {
            pageNum = pageParam.pageNum;
            pageSize = pageParam.limit;
            totalSize = pageParam.totalSize;
            totalPage = pageParam.totalPage;
            isFirstPage = (pageNum == 1);
            isLastPage = (pageNum == totalPage);
            PageInterceptor.PARAM_THREAD_LOCAL.remove();
        }
    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(Integer totalSize) {
        this.totalSize = totalSize;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    public Boolean getFirstPage() {
        return isFirstPage;
    }

    public void setFirstPage(Boolean firstPage) {
        isFirstPage = firstPage;
    }

    public Boolean getLastPage() {
        return isLastPage;
    }

    public void setLastPage(Boolean lastPage) {
        isLastPage = lastPage;
    }

    @Override
    public String toString() {
        return "PageResult{" +
                "isFirstPage=" + isFirstPage +
                ", isLastPage=" + isLastPage +
                ", pageNum=" + pageNum +
                ", pageSize=" + pageSize +
                ", totalSize=" + totalSize +
                ", totalPage=" + totalPage +
                ", data=" + data +
                '}';
    }
}

2.6 簡單測試下

@Test
public void selectForPage() {
    // 該查詢進行分頁,指定第幾頁和每頁數量
    PageInterceptor.startPage(1,4);
    List<UserInfoDO> all = userMapper.findAll();
    PageResult<UserInfoDO> result = new PageResult<>(all);
    // 分頁結果列印
    log.info("總記錄數:{}", result.getTotalSize());
    log.info("list:{}", result.getData());
    log.info("result:{}", result);
}

使用方法基本1.3完全一致吧,只是封裝成了我自己的分頁結果集。

  • 日誌如下:
....: ==>  Preparing: SELECT id, user_name, age, create_time FROM user_info_pageable limit 4 
....: ==> Parameters: 
....: <==      Total: 4
....: 總記錄數:6
....: list:[UserInfoDO(id=1, userName=張三, age=22, createTime=2019-10-08T20:52:46), UserInfoDO(id=2, userName=李四, age=21, createTime=2019-12-23T20:22:54), UserInfoDO(id=3, userName=王二, age=22, createTime=2019-12-23T20:23:15), UserInfoDO(id=4, userName=馬五, age=20, createTime=2019-12-23T20:23:15)]
....: result:PageResult{isFirstPage=true, isLastPage=false, pageNum=1, pageSize=4, totalSize=6, totalPage=2, data=[UserInfoDO(id=1, userName=張三, age=22, createTime=2019-10-08T20:52:46), UserInfoDO(id=2, userName=李四, age=21, createTime=2019-12-23T20:22:54), UserInfoDO(id=3, userName=王二, age=22, createTime=2019-12-23T20:23:15), UserInfoDO(id=4, userName=馬五, age=20, createTime=2019-12-23T20:23:15)]}

通過日誌分析,發現普通的SELECT * FROM user_info_pageable 被重新組裝成SELECT * FROM user_info_pageable limit 4,說明攔截器實現的分頁成功。

三、總結

兩種方式:Pagehelper 分頁和自己實現,根據實際情況自己選用吧。

  1. Pagehelper 分頁示例程式碼
  2. Mybatis 攔截器實現分頁示例程式碼

3.1 日常求贊

  1. 祖傳祕籍 Spring Boot 葵花寶典 開源中,歡迎前來吐槽,提供線索!
  2. 九陽神功 【Java 知識筆記本】 開源中,歡迎前來吐槽,提供線索!

3.2 文化交流

  1. 風塵部落格
  2. 風塵部落格-掘金
  3. 風塵部落格-部落格園
  4. 風塵部落格-CSDN
  5. Github

相關文章