温馨提示×

mybatis分页插件pagehelper怎么用

小亿
87
2023-12-21 15:45:52
栏目: 编程语言

MyBatis 分页插件 PageHelper 是一个开源的分页插件,可以用于实现 MyBatis 的分页查询功能。

以下是使用 PageHelper 插件的步骤:

  1. 引入依赖:在 Maven 中,添加以下依赖到你的项目中:
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>最新版本</version>
</dependency>
  1. 配置插件:在 MyBatis 的配置文件中,添加 PageHelper 插件的配置项:
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <properties>
            <!-- 分页参数配置 -->
            <!-- dialect 属性用于配置数据库方言,默认为 mysql -->
            <property name="dialect" value="mysql"/>
            <!-- rowBoundsWithCount 属性用于配置是否需要查询总数,默认为 false -->
            <property name="rowBoundsWithCount" value="true"/>
            <!-- reasonable 属性用于配置是否启用合理化查询,默认为 false -->
            <property name="reasonable" value="true"/>
        </properties>
    </plugin>
</plugins>
  1. 在需要分页的查询方法中,使用 PageHelper.startPage 方法启动分页,然后执行查询语句:
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

...

// 在查询之前调用 PageHelper.startPage 方法,传入当前页码和每页显示的数量
PageHelper.startPage(pageNum, pageSize);

// 执行查询语句
List<Entity> entities = yourMapper.yourQueryMethod();

// 使用 PageInfo 对象包装查询结果,并传入需要显示的页码数量
PageInfo<Entity> pageInfo = new PageInfo<>(entities, navigatePages);

其中,pageNum 参数表示当前页码,pageSize 参数表示每页显示的数量,yourMapper.yourQueryMethod() 表示你的查询语句的方法。

  1. 使用 PageInfo 对象获取分页相关信息:
// 获取当前页码
int currentPage = pageInfo.getPageNum();

// 获取每页显示的数量
int pageSize = pageInfo.getPageSize();

// 获取总记录数
long total = pageInfo.getTotal();

// 获取总页数
int pages = pageInfo.getPages();

// 获取查询结果
List<Entity> resultList = pageInfo.getList();

这样就可以使用 PageHelper 插件进行分页查询了。

0