MyBatis分页插件PageHelper

官方文档:https://pagehelper.github.io/docs/

我们在  mybatis和spring整合(基于xml) 的基础上使用分页插件。

引入分页插件 

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.11</version>
</dependency>

配置拦截器插件

特别注意,新版拦截器是 com.github.pagehelper.PageInterceptor。 com.github.pagehelper.PageHelper 现在是一个特殊的 dialect 实现类,是分页插件的默认实现类,提供了和以前相同的用法。

① 在 MyBatis 配置 xml 中配置拦截器插件

<!--
    plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下:
    properties?, settings?,
    typeAliases?, typeHandlers?,
    objectFactory?,objectWrapperFactory?,
    plugins?,
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
        <property name="param1" value="value1"/>
	</plugin>
</plugins>

② 在 Spring 配置文件中配置拦截器插件

使用 spring 的属性配置方式,可以使用 plugins 属性像下面这样配置:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- 注意其他配置 -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!--使用下面的方式配置参数,一行配置一个 -->
          <value>
            params=value1
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>

如何在代码中使用

mapper接口:

List<User> listAll();

mapper xml:

<select id="listAll" resultType="com.harvey.po.User">
    select * from user
</select>

测试代码:

//第一种方式:
//第几页,每页几条数据
Page<User> page = PageHelper.startPage(1, 2);
//紧跟着的第一个select方法会被分页
List<User> userList = userMapper.listAll();
System.out.println("count:" + page.getTotal());
System.out.println("user list :" + userList);

//第二种方式:
//PageHelper.startPage(1, 2);
//List<User> userList = userMapper.listAll();
//PageInfo pageInfo = new PageInfo<User>(userList);
//System.out.println("count:" + pageInfo.getTotal());
//System.out.println("user list :" + userList);

 

posted @ 2022-03-20 15:25  残城碎梦  阅读(138)  评论(0编辑  收藏  举报