(TT)分页插件PageHelper

简述

PageHelper分页插件,与Mybatis配合使用实现分页功能十分方便。
该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。

原理

实现了mybatis的拦截器接口,对sql语句进行编辑,然后把修改后sql语句设置回去。

使用方法

1. 添加jar包
mybatis-paginator-1.2.15.jar
pagehelper-3.4.2.jar
2. 修改sqlMapConfig.xml,添加分页插件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 配置分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 指定使用的数据库是什么 -->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

</configuration>

3. 测试使用

public class TestPageHelper {
    @Test
    public void testPageHelper() throws Exception {
        //1、获得mapper代理对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
        TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);
        //2、设置分页(第一页,每页30条数据)
        PageHelper.startPage(1, 30);
        //3、执行查询
        TbItemExample example = new TbItemExample();
        List<TbItem> list = itemMapper.selectByExample(example);
        //4、取分页后结果
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        System.out.println("total:" + total);
        int pages = pageInfo.getPages();
        System.out.println("pages:" + pages);
        int pageSize = pageInfo.getPageSize();
        System.out.println("pageSize:" + pageSize);
    }
}

4.总结
代码中PageHelper.startPage(1, 30);直接作用在下一条要执行的sql语句上,所以list中取出的数据已经是要返回给前端的数据。
pageInfo对象内实现了一些方法,例如计数统计等。

猜你喜欢

转载自blog.csdn.net/FortressBesieged/article/details/82466529