PageHelper
Mybatis分页插件
支持Oracle、Mysql、MariaDB、SQLite、Hsqldb、PostgreSQL六种数据库
不支持SQL Server,Java开发很少使用SQL数据库
添加jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
配置拦截器
在Mybatis配置文件中,配置拦截器插件
分页原理
在Mybatis执行SQL语句之前,拦截获取SQL
对其进行处理,添加limit等语句
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">
<!-- 配置数据库的方言 -->
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
常用代码
设置分页信息
//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
//紧跟着的第一个select方法会被分页
List<Country> list = countryMapper.selectIf(1);
取分页信息,方式一
//分页后,实际返回的结果list类型是Page<E>,如果想取出分页信息,需要强制转换为Page<E>,
Page<Country> listCountry = (Page<Country>)list;
listCountry.getTotal();
取分页信息,方式二
//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectAll();
//用PageInfo对结果进行包装
PageInfo page = new PageInfo(list);
PageInfo
//测试PageInfo全部属性
//PageInfo包含了非常全面的分页属性
assertEquals(1, page.getPageNum());
assertEquals(10, page.getPageSize());
assertEquals(1, page.getStartRow());
assertEquals(10, page.getEndRow());
assertEquals(183, page.getTotal());
assertEquals(19, page.getPages());
assertEquals(1, page.getFirstPage());
assertEquals(8, page.getLastPage());
assertEquals(true, page.isFirstPage());
assertEquals(false, page.isLastPage());
assertEquals(false, page.isHasPreviousPage());
assertEquals(true, page.isHasNextPage());
测试
public class TestPageHelper {
@Test
public void testPageHelper() throws Exception {
// 1.在mybatis的配置文件中配置分页插件
// 2.在执行查询之前配置分页条件。使用PageHelper的静态方法
PageHelper.startPage(1, 10);
// 3.执行查询
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext-dao.xml");
TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);
// 创建Example对象
TbItemExample example = new TbItemExample();
// Criteria criteria = example.createCriteria();
List<TbItem> list = itemMapper.selectByExample(example);
// 4.取分页信息。使用PageInfo对象取。
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
System.out.println("总记录数:" + pageInfo.getTotal());
System.out.println("总记页数:" + pageInfo.getPages());
System.out.println("返回的记录数:" + list.size());
}
}