Mybatis分页插件pagehelper使用方法

1. 需要引入PageHelper的jar包

如果没有使用maven的话直接把jar包导入到lib目录下,如果使用了maven要在pom文件中引入依赖。

        <dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>3.4.2-fix</version>
		</dependency>

2. 在mybatis的全局配置文件SqlMapConfig.xml中配置该插件

<?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" />
		</plugin>
	</plugins>
</configuration>

3. 在执行sql前添加插件,完成分页功能

package lx.test.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 lx.test.mapper.TbItemMapper;
import lx.test.pojo.TbItem;
import lx.test.pojo.TbItemExample;
import lx.test.pojo.TbItemExample.Criteria;

public class PageHelperTest {

	@Test
	public void testPageHelper(){
		//初始化spring容器
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
		//从容器中获取Mapper代理对象
		TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);
		//执行sql查询之前设置分页信息,使用pageHelper的startPage方法
		PageHelper.startPage(1, 10);
		//执行查询
		TbItemExample example = new TbItemExample();
		List<TbItem> list = itemMapper.selectByExample(example);
        for(TbItem item : list){
			System.out.println(item.getTitle());
		}
		//取分页信息PageInfo.1总记录数2.总页数,每页显示条数
		PageInfo<TbItem> pageInfo = new PageInfo<>(list);
		System.out.println(pageInfo.getTotal());
		System.out.println(pageInfo.getPages());
		System.out.println(list.size());
	}
}

4.测试结果

猜你喜欢

转载自blog.csdn.net/bigLiu66/article/details/86476431