MyBaits分页插件-PageHelper

MySql对分页的支持

MySql对分页的支持是通过limit字句实现的:
Limit [offset,rows]
offset是相对与首行的偏移量(首行是0),rows是返回条数
例如:每页30条数据,取第一页:select * from tableName limit 0,30;
每页30条数据,取第二页:select * from tableName limit 10,30;

由上可知,分页通过limit关键字就可以实现,但是如果项目中用的是MyBatis逆向工程,我们不可能去修改逆向工程的生成的查询语句,此时最好的选择就是MyBatis的分页插件PageHelper。

PageHelper

该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。他的原理是利用Mybatis拦截器,再查询数据库的时候,拦截下sql,然后进行修改,从而实现分页。原理可以用下边一幅图来解释:
这里写图片描述

使用步骤

1、添加pom依赖

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

2、在MyBatis配置文件中进行配置

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

3、分页测试

public class TestPageHelper {

    @Test
    public void testPageHelper() throws Exception{
        //获得mapper代理对象,从spring容器中获得
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
        TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);//查商品列表
        //设置分页
        //只对下边的第一个select有效,再来一个就失效了
        PageHelper.startPage(1, 30);
        //执行查询
        TbItemExample example = new TbItemExample();
        List<TbItem> list = itemMapper.selectByExample(example);
        //取分页后结果
        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);
    }
}

结语

就这样,分页功能就实现了。pagehelper的关键就是设置分页的时候,插入“PageHelper.startPage(1, 30);”这句代码,对sql进行编辑,然后执行编辑后的语句。

猜你喜欢

转载自blog.csdn.net/ldb987/article/details/81302125