【防坑指南】使用Mybatis分页插件PageHelper为什么PageInfo对象出现null的原因

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39148512/article/details/80182095

在mybatis中,先导入pagehelper.jar所需的jar包,然后在sqlMapConfig,xml中配置插件

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

配置好插件后就进行测试

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<TbItem> list = mapper.selectByExample(example);

        //设置PageHelper分页信息,1表示当前第1页,10表示当前页的条数为10
        PageHelper.startPage(1, 10);
        
        //获取分页信息
        PageInfo<TbItem> 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<TbItem> list = mapper.selectByExample(example);        //获取分页信息        PageInfo<TbItem> 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]}

猜你喜欢

转载自blog.csdn.net/weixin_39148512/article/details/80182095