天天看点

mybatis中pageHelper的配置使用

第一步:导入pageHelper的jar包

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.4</version>
</dependency>
           

第二步:在mybatsi的总的配置文件中配置分页插件,说明示例如下

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

第三步:使用

package cn.gxm.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 cn.gxm.mapper.TbItemMapper;
import cn.gxm.pojo.TbItem;
import cn.gxm.pojo.TbItemExample;

/**
 * 测试mybatsi的插件pagehelper的使用
 * @author xiaomi
 *
 */
public class TestPageHelper {

	@Test
	public void testPagehelper() {
		//1)在mybatsi的总的配置文件中配置分页插件
		//2)在使用mybatis查询之前使用pagehelper的静态方法,设置开始页码(从1开始),每页多少条
		PageHelper.startPage(1,10);
		
		//3)使用Mybatis查询信息,放在list中
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
		TbItemMapper tbItemMapper = applicationContext.getBean(TbItemMapper.class);
		TbItemExample example = new TbItemExample();
		List<TbItem> list = tbItemMapper.selectByExample(example);
		
		//4)使用pageInfo接收mybatis查询的结果集合
		PageInfo<TbItem> info = new PageInfo<>(list);
		
		//5)info中会获取原本的数据(本来查询的结果)
		System.out.println("原本查询的所有数据总条数"+info.getTotal());
		
		//6)而此时原本使用Mybatis查询信息,放在list中的数据已经是截取之后的了
		System.err.println(list.size());
	}

       //输出如下:
       //10
       //原本查询的所有数据总条数3096


}
           

关于该插件在mybatis的逆向工程的使用中,需要在网上找一些别人改好的版本,因为原始的pagehelper在使用时会出现一些异常!但是普通的mybatsi没有问题!

继续阅读