Mybatis分页插件 - PageHelper(spring整合)

如果你也在用Mybatis,建议尝试该分页插件,这个一定是最方便使用的分页插件。

该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。

原理:在执行sql语句之前,拦截sql语句,拼接limit就可以实现

分页插件的使用:

第一步:把PageHelper依赖的jar包添加到工程中。

第二步:在Mybatis配置xml中配置拦截器插件:

<plugins>

    <!-- com.github.pagehelperPageHelper类所在包名 -->

    <plugin interceptor="com.github.pagehelper.PageHelper">

        <property name="dialect" value="mysql"/>

        <!-- 该参数默认为false -->

        <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->

        <!-- startPage中的pageNum效果一样-->

        <property name="offsetAsPageNum" value="true"/>

        <!-- 该参数默认为false -->

        <!-- 设置为true时,使用RowBounds分页会进行count查询 -->

        <property name="rowBoundsWithCount" value="true"/>

        <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->

        <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->

        <property name="pageSizeZero" value="true"/>

        <!-- 3.3.0版本可用 分页参数合理化,默认false禁用 -->

        <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->

        <!-- 禁用合理化时,如果pageNum<1pageNum>pages会返回空数据 -->

        <property name="reasonable" value="true"/>

    </plugin>

</plugins>

这里的com.github.pagehelper.PageHelper使用完整的类路径。

其他五个参数说明:

1. 增加dialect属性,使用时必须指定该属性,可选值为oracle,mysql,mariadb,sqlite,hsqldb,postgresql,没有默认值,必须指定该属性

2. 增加offsetAsPageNum属性,默认值为false,使用默认值时不需要增加该配置,需要设为true时,需要配置该参数。当该参数设置为true时,使用RowBounds分页时,会将offset参数当成pageNum使用,可以用页码和页面大小两个参数进行分页。

3. 增加rowBoundsWithCount属性,默认值为false,使用默认值时不需要增加该配置,需要设为true时,需要配置该参数。当该参数设置为true时,使用RowBounds分页会进行count查询。

4. 增加pageSizeZero属性,默认值为false,使用默认值时不需要增加该配置,需要设为true时,需要配置该参数。当该参数设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果(相当于没有执行分页查询,但是返回结果仍然是Page类型)。

5.增加reasonable属性,默认值为false,使用默认值时不需要增加该配置,需要设为true时,需要配置该参数。具体作用请看上面配置文件中的注释内容。

第三步:在执行查询之前配置分页条件。使用PageHelper的静态方法

PageHelper.startPage(page,rows);

第四步:执行查询

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");

TbItemMapper itemMapper = applicationContext.getBean(Student.class);

第五步:创建Example对象

StudentExample example = new StudentExample ();

List<Student> list = StudentMapper.selectByExample(example);

第六步:取分页信息。使用PageInfo对象取。

PageInfo<Student> pageInfo = new PageInfo<>(list);

System.out.println("总记录数:" + pageInfo.getTotal());

System.out.println("总记页数:" + pageInfo.getPages());

System.out.println("返回的记录数:" + list.size());

重要提示:

1、PageHelper.startPage方法重要提示

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

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

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

3、 分页插件不支持关联结果查询

猜你喜欢

转载自blog.csdn.net/aubrey_cr7/article/details/80716187