在mybatis中,先导入pagehelper.jar所需的jar包,然后在sqlMapConfig,xml中配置插件
配置好插件后就进行测试public class TestPagehelper {
@Test
public void test(){
//读取applicationContext配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
//获取mapper代理对象
TbItemMapper mapper = context.getBean(TbItemMapper.class);
//执行查询语句
TbItemExample example = new TbItemExample();
List list = mapper.selectByExample(example);
//设置PageHelper分页信息,1表示当前第1页,10表示当前页的条数为10
PageHelper.startPage(1, 10);
//获取分页信息
PageInfo pageInfo=new PageInfo<>(list);
System.out.println(pageInfo);
}
}
输出结果为:PageInfo{pageNum=0, pageSize=0, size=0, startRow=0, endRow=0, total=0, pages=0,
list=null, firstPage=0, prePage=0, nextPage=0, lastPage=0, isFirstPage=false,
isLastPage=false, hasPreviousPage=false, hasNextPage=false, navigatePages=0, navigatepageNums=null}
为什么PageInfo对象为null呢?
原因就是:必须得先设置PageHelper,然后执行查询语句
public class TestPagehelper {
@Test
public void test(){
//读取applicationContext配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
//获取mapper代理对象
TbItemMapper mapper = context.getBean(TbItemMapper.class);//设置PageHelper分页信息,1表示当前第1页,10表示当前页的条数为10
PageHelper.startPage(1, 10); //执行查询语句 TbItemExample example = new TbItemExample();List list = mapper.selectByExample(example); //获取分页信息 PageInfo pageInfo=new PageInfo<>(list);System.out.println(pageInfo);}}查询成功
PageInfo{pageNum=1, pageSize=10, size=10, startRow=1, endRow=10, total=934, pages=94, list=Page{pageNum=1, pageSize=10, startRow=0, endRow=10, total=934, pages=94}, firstPage=1, prePage=0, nextPage=2, lastPage=8, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=8, navigatepageNums=[1, 2, 3, 4, 5, 6, 7, 8]}