mybatis分页插件PageHelper的使用

引入jar:

maven:

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->

<dependency>

    <groupId>com.github.pagehelper</groupId>

    <artifactId>pagehelper</artifactId>

    <version>5.1.2</version>

</dependency>

 

配置拦截器插件:

第一种:在 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 配置文件中配置拦截器插件

<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接口方式的调用。

Page<Object> page = PageHelper.startPage(1, 10);

List<Country> list = countryMapper.selectUser();

 

第二种,Mapper接口方式的调用。

Page<Object> page = PageHelper.offsetPage(1, 10);

List<Country> list = countryMapper.selectUser();

//获取参数

获取当前页码:    page.getPageNum()

获取总记录数:    page.getTotal();

获取每页记录数:      page.getPageSize();

获取总页码:         page.getPages();

 

重要提示

PageHelper.startPage方法重要提示

只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询(Select)方法会被分页。

请不要配置多个分页插件

请不要在系统中配置多个分页插件(使用Spring时,mybatis-config.xml和Spring<bean>配置方式,请选择其中一种,不要同时配置多个分页插件)!

分页插件不支持带有for update语句的分页

对于带有for update的sql,会抛出运行时异常,对于这样的sql建议手动分页,毕竟这样的sql需要重视。

分页插件不支持嵌套结果映射

由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少,所以无法保证分页结果数量正确。

原文地址:https://www.cnblogs.com/it-xiaoBai/p/10814895.html