PageHelper插件使用(mybatis相关)

PageHelper插件使用


一、PageHelper介绍

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

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


二、使用步骤

(1)导包。版本为:parent中的3.4.2-fix

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

(2)在mybatis的配置文件中配置插件(SqlMapConfig.xml):

<!--配置插件-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
        <property name="dialect" value="mysql"/>
    </plugin>
</plugins>

(3)测试

package cn.e3mall.pagehelper;

import cn.e3mall.dao.TbItemMapper;
import cn.e3mall.entity.TbItem;
import cn.e3mall.entity.TbItemExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * PageHelper插件测试
 * Author: xushuai
 * Date: 2018/5/12
 * Time: 16:48
 * Description:
 */
public class PageHelperTest {


    @Test
    public void pageHelerTest(){
        //加载spring配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
        //获取mybatisMapper对象
        TbItemMapper mapper = ac.getBean(TbItemMapper.class);
        //设置分页信息
        /*
         * 参数:
         *      1、当前页
         *      2、当前记录条数
         */
        PageHelper.startPage(1,10);
        TbItemExample example = new TbItemExample();
        //执行查询
        List<TbItem> tbItems = mapper.selectByExample(example);
        //获取分页信息对象
        PageInfo<TbItem> pageInfo = new PageInfo<>(tbItems);
        //相关数据展示
        System.out.println("总记录数" + pageInfo.getTotal());//总记录数
        //System.out.println("数据" + pageInfo.getList());//数据的list集合
        System.out.println("总页数" + pageInfo.getPages());//总页数
        System.out.println("每页记录数" + pageInfo.getSize());//每页记录数
    }
}

运行结果:

PageInfo方法列表:


猜你喜欢

转载自blog.csdn.net/qq1031893936/article/details/80292743
今日推荐