1. 程式人生 > >【防坑指南】使用Mybatis分頁外掛PageHelper為什麼PageInfo物件出現null的原因

【防坑指南】使用Mybatis分頁外掛PageHelper為什麼PageInfo物件出現null的原因

在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]}