SpringBoot 使用MyBatis分页插件实现分页功能
- 1、集成pagehelper
- 2、配置pagehelper
- 3、编写代码
- 4、分页效果
案例地址: https://gitee.com/vinci99/paging-pagehelper-demo/tree/master
1、集成pagehelper
<!-- 集成pagehelper -->
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.6</version>
</dependency>
2、配置pagehelper
这里使用application.properties类型配置文件来做例子
#配置pagehelper
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
3、编写代码
创建一个持久化对象TestUserPO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TestUserPO {/*** @description: 编号**/private Integer id;/*** @description: 姓名**/private String name;}
编写在Mapper中编写SQL语句查询与之对应的表
<!-- SQL这里不用写分页 --><select id="getInfo" resultType="com.vinci.demo.entity.TestUserPO">SELECTid,nameFROM test_user</select>
在业务层调用Mapper接口获取数据并分页;需要注意:PageHelper.startPage(pageNum,pageSize)必须写在查询前面,否则将不会生效
/*** @description: mapper接口* @author: Vinci* @date: 2023/9/2 12:23**/@Resourceprivate TestUserMapper testUserMapper;/*** @description: 测试分页* @author: Vinci* @date: 2023/9/2 12:18**/@Overridepublic PageInfo<TestUserPO> getInfo(Integer pageNum, Integer pageSize) {PageHelper.startPage(pageNum,pageSize);List<TestUserPO> info = testUserMapper.getInfo();return new PageInfo<>(info);}
继续编写Controller层代码,将数据返回给前端
/*** @description: 日志服务**/private static final Logger log = LoggerFactory.getLogger(TestController.class);/*** @description: 业务层接口**/@Resourceprivate TestUserService testUserService;/*** @description: 测试分页* @author: Vinci* @param pageNum 页码* @param pageSize 页长 (每页多少条数据)* @date: 2023/9/2 12:18**/@GetMapping("/getInfo")public Object getInfo(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,@RequestParam(value = "pageSize",defaultValue = "15")Integer pageSize){try{return testUserService.getInfo(pageNum,pageSize);}catch (Exception e){log.error("发现异常,",e);return e.getMessage();}}