Mybatis-分页插件PageHelper使用

分页插件PageHelper--Mybatis分页插件

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

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

 

使用方法

1、加入PageHelper依赖

		
		
			com.github.pagehelper
			pagehelper
			4.1.4
		

2、在SqlMapConfig文件中导入此插件 plugins-plugin

  • 拦截器到导入的包找全限定名interceptor:com.github.pagehelper.PageHelper
  • 数据库类型

	
	    
	    	 
	        
	    
	

3、测试,使用步骤

使用前,你的项目必须有一个数据库查询,因为PageHelper的startPage方法只针对其下第一个数据库查询生效

PageHelper.startPage(num,pageSize),num是指当前页数,pageSize是指一页多少条记录

使用步骤

  • 初始化spring容器,只要初始化dao层
  • 得到一个查询的类
  • 执行sql语句之前设置分页信息,使用PageHelper.startPage(num,pageSize)(此方法只对下面第一个sql语句查询生效)
  • 执行mysql查询
  • 取分页信息,PageInfo,可以取到总记录数、总页数、当前页码等

测试代码

package com.bbs.pagehelper;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xue.bbs.dao.ArticleMapper;
import com.xue.bbs.pojo.Article;

public class PageHelperTest {
	
	@SuppressWarnings("resource")
	@Test
	public void test() {
		//初始化spring容器
		ApplicationContext applicationContext = new 
				ClassPathXmlApplicationContext("classpath:spring/ApplicationContext.xml");
		
		//得到一个查询的bean
		ArticleMapper articleMapper = applicationContext.getBean(ArticleMapper.class);
		
		//设置分页信息 当前页1 一页记录数3条
		PageHelper.startPage(1, 3);
		
		//执行mysql查询
		List
list = articleMapper.selectAll(0); //得到分页信息 PageInfo
pageInfo = new PageInfo<>(list); System.out.println(pageInfo.getTotal());//获得总记录数 System.out.println(pageInfo.getPageNum());//获得当前页数 System.out.println(pageInfo.getSize());//获得一页有多少条记录 System.out.println(pageInfo.getPages());//获得多少页 } }

 


 

你可能感兴趣的:(SSM)