共計(jì) 1279 個(gè)字符,預(yù)計(jì)需要花費(fèi) 4 分鐘才能閱讀完成。
Java 分頁插件 PageHelper 可以很方便地實(shí)現(xiàn)分頁功能。下面是使用 PageHelper 的步驟:
- 導(dǎo)入 PageHelper 依賴
在項(xiàng)目的 pom.xml 文件中添加 PageHelper 依賴:
com.github.pagehelper
pagehelper
版本號
- 配置 PageHelper
在 Spring 的配置文件中添加 PageHelper 的配置信息,例如在 application.properties 文件中添加以下配置:
# 設(shè)置 數(shù)據(jù)庫 方言,支持的數(shù)據(jù)庫有:oracle, mysql, mariadb, sqlite, hsqldb, postgresql, db2, sqlserver, informix
pagehelper.helper-dialect=mysql
# 設(shè)置為 true 時(shí),會將 RowBounds 第一個(gè)參數(shù) offset 當(dāng)成 pageNum 頁碼使用
pagehelper.offset-as-page-num=true
# 設(shè)置為 true 時(shí),使用 RowBounds 分頁會進(jìn)行 count 查詢
pagehelper.row-bounds-with-count=true
# 設(shè)置為 true 時(shí),如果 pageSize= 0 或者 RowBounds.limit = 0 就會查詢出全部的結(jié)果
pagehelper.reasonable=false
# 設(shè)置為 true 時(shí),如果 pageSize= 0 或者 RowBounds.limit = 0 時(shí)會查詢出全部的結(jié)果
pagehelper.support-methods-arguments=false
# 設(shè)置為 true 時(shí),表示支持從接口中讀取 pageNum 和 pageSize
pagehelper.params=pageNum=page;pageSize=limit;pageSizeZero=zero;reasonable=heli;count=countSql
- 在查詢方法中使用 PageHelper 進(jìn)行分頁
在需要進(jìn)行分頁的查詢方法中,添加以下代碼:
PageHelper.startPage(pageNum, pageSize);
List list = yourMapper.selectByExample(example);
其中,pageNum 表示當(dāng)前頁碼,pageSize 表示每頁顯示的數(shù)據(jù)數(shù)量。startPage 方法會自動將后續(xù)的查詢語句進(jìn)行分頁。
- 獲取分頁結(jié)果
使用 PageInfo 來獲取分頁結(jié)果,例如:
PageInfo pageInfo = new PageInfo(list);
long total = pageInfo.getTotal(); // 總記錄數(shù)
int pages = pageInfo.getPages(); // 總頁數(shù)
以上就是使用 PageHelper 插件進(jìn)行分頁的基本步驟。需要注意的是,PageHelper 插件默認(rèn)使用 RowBounds 方式進(jìn)行分頁,如果你使用的是 MyBatis 的 Mapper 接口方式,可以通過設(shè)置 pagehelper.support-methods-arguments 為 true 來支持從接口中讀取 pageNum 和 pageSize 參數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完