前言
如果用mybatis寫分頁查詢,比較麻煩,需要先寫獲取count的select語句,然後寫分頁查詢語句。這裏使用一個強大的插件 pagehelper ,可以幫助開發者快速實現分頁。
優點:
- 和sqlmapper.xml文件解耦,以插件形式實現,避免直接寫分頁查詢sql
- 方便、快速
引入pagehelper依賴
pom.xml中引入相關依賴
<!-- 添加分頁插件 pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
application.yml中配置
# 分頁插件
pagehelper:
helperDialect: mysql
reasonable: false
params: count=countSql
supportMethodsArguments: true
說明:
helperDialect:指定數據庫,不指定會自動檢測數據庫類型
reasonable:合理化參數,默認false,
true:頁碼小於1,查詢第一頁數據,頁碼大於總數時,返回最後一頁數據;
false:頁碼小於等於1都返回第一頁數據,頁碼大於總數時返回空
supportMethodsArguments:默認false,true:分頁插件根據params中取值,找到合適值,就自動分頁
增加接口
dao
List<UserMoudel> findAllByPage();
service
PageInfo<UserMoudel> findAllByPage(int page, int offset);
serviceImpl,重點是這裏的實現,也是使用 pagehelper的核心代碼
@Override
public PageInfo<UserMoudel> findAllByPage(int page, int offset) {
// 這一句是核心
PageHelper.startPage(page,offset);
List<UserMoudel> all = dao.findAllByPage();
return new PageInfo<UserMoudel>(all);
}
controller
@ApiOperation(value = "分頁查詢用戶信息")
@GetMapping("/findAllByPage")
@ResponseBody
public PageInfo<UserMoudel> findAllByPage(@RequestParam(value = "當前頁碼",required = true) int page,@RequestParam(value = "每頁數量",required = true) int offset){
return userSvc.findAllByPage(page,offset);
}
測試分頁查詢接口
測試通過
問題總結
application.yml中pagehelper配置問題
1 指定數據庫一定要使用 helperDialect,不要使用 dialect,否則,spring boot程序啓動失敗,出現以下異常:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-06-14 13:56:42.839 ERROR 2104 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration': Invocation of init method failed; nested exception is com.github.pagehelper.PageException: java.lang.ClassNotFoundException: mysql
從異常中看出,找不到mysql,然後debug,發現是配置中指定數據庫的問題