mybatis 分页查询_MyBatis之分页查询:MyBatis PageHelper
MyBatis,作為目前流行的ORM框架,大大方便了日常開發。而對于分頁查詢,雖然可以通過SQL的limit語句實現,但是比較繁瑣。而MyBatis PageHelper的出現,則解決了這一痛點。這里將介紹如何在Spring Boot、MyBatis的環境中通過MyBatis PageHelper高效方便的實現分頁查詢
配置
1. 添加Maven依賴
<!--MyBatis 分頁插件: MyBatis PageHelper--> <dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.5</version> </dependency>2. 添加配置
在application.properties配置文件中添加MyBatis PageHelper的配置項
# PageHelper 分頁插件配置 pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql分頁查詢
通過 MyBatis PageHelper 進行分頁查詢實際上非常簡單,只需在service(或mapper)方法執行查詢前,調用一次 PageHelper.startPage(pageNum,pageSize) 來設置分頁查詢參數即可,其中pageNum 為記錄頁數,pageSize 為單頁記錄數量。此時service(或mapper)方法的查詢結果就是分頁后的結果了。如果期望獲得相關的分頁信息,還可以將查詢結果封裝到PageInfo對象中,以獲得總頁數、總記錄數、當前頁數等相關分頁信息
現在通過一個實際示例,來具體演示操作,這里我們提供了一個分頁查詢的Controller
/*** 分頁查詢* @param pageNum 記錄頁數* @param pageSize 單頁記錄數量* @return*/ @ResponseBody @RequestMapping("/findPage") public List<Student> findPage(@RequestParam int pageNum, @RequestParam int pageSize) {// 設置分頁查詢參數PageHelper.startPage(pageNum,pageSize);List<Student> studentList = studentService.findList();for(Student student : studentList) {System.out.println("element : " + student);}// 封裝分頁查詢結果到 PageInfo 對象中以獲取相關分頁信息PageInfo pageInfo = new PageInfo( studentList );System.out.println("總頁數: " + pageInfo.getPages());System.out.println("總記錄數: " + pageInfo.getTotal());System.out.println("當前頁數: " + pageInfo.getPageNum());System.out.println("當前頁面記錄數量: " + pageInfo.getSize());return pageInfo.getList(); }service方法中所調用的查詢SQL如下所示,可以看到,SQL中無需使用limit語句
...<resultMap id="studentResultMap" type="com.aaron.springbootdemo.pojo.Student"><id property="id" column="id" jdbcType="INTEGER"/><result property="username" column="username" jdbcType="VARCHAR"/><result property="sex" column="sex" jdbcType="VARCHAR"/><result property="address" column="address" jdbcType="VARCHAR"/></resultMap><select id="findList" parameterType="String" resultMap="studentResultMap"> SELECT * FROM user</select>...測試結果如下所示
查詢第一頁:
查詢第二頁:
Note:
PageHelper.startPage(pageNum,pageSize) 只對其后的第一次SQL查詢進行分頁。故若需進行分頁查詢,必須每次在service(或mapper)方法執行SQL查詢前調用PageHelper.startPage(pageNum,pageSize) 方法
總結
以上是生活随笔為你收集整理的mybatis 分页查询_MyBatis之分页查询:MyBatis PageHelper的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 光纤通道速率查看_基于OM3/OM4的光
- 下一篇: 冰豹lua驱动设置_通过编写“猜数字”游