PageHelper分页插件用法

578 阅读1分钟

介绍

PageHelper是mybatis的通用分页插件,通过mybatis的拦截器实现分页功能,拦截sql查询请求,添加分页语句,实现分页查询功能。
原理:

image.png

ThreadLocal是一个线程级别的变量,把分页参数(page,size)设置到里面
当一次请求来到服务端,服务端就看开启一个线程,线程开始调用Controller,然后调用Service,最后调用Dao。 只要在这个线程内,任何一个方法都能拿到线程ThreadLocal里的参数。在Dao层通过mybatis拦截器,拦截到查询请求,把ThreadLocal里的参数取出来,由PageHelper把参数拼装到sql语句中。

如何使用PageHelper

配置依赖

<!--分页查询插件-->
<dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.4</version>
</dependency>

配置数据库类型

根据不同到数据库,分页拼装代码不同,这里拿mysql举例

pagehelper:
    helper-dialect: mysql

测试分页查询

mapper

@Mapper
public interface TestMapper {
   /**
    * 分页查询
    * @param listRequest 查询条件
    * @return
    */
   Page<CourseBase> findList(ListRequest listRequest);
}

xml

<!--分页查询-->
<select id="findList" resultType="com.xx.xx.Info">
    SELECT * FROM base
</select>

执行方法

@Test
public void testPageHelper(){
    // 设置分页参数
    PageHelper.startPage(1, 10);
    Page<Info> info = TestMapper.findList();
}