MyBatis+PageHelper实现分页

寿高阳
2023-12-01

PageHelper是一个运行在MyBatis基础之上的API库,用于简单地实现对表中数据进行分页查询。

1、数据

CREATE TABLE `student` (
  `id` char(36) PRIMARY KEY COMMENT '主键',
  `name` varchar(18) NOT NULL COMMENT '姓名',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别:1-男,2-女',
  `mobile` char(11) NOT NULL COMMENT '手机号',
  `address` varchar(150) NOT NULL COMMENT '家庭地址'
);

insert into `student`(`id`,`name`,`sex`,`mobile`,`address`) values ('059ba7c5-34d4-48bf-9e76-13f52a95e229','萧婷',2,'13031070239','新疆自治区乌鲁木齐市沙依巴克区雅玛里克山街道新疆三建家属院'),('0cc9987d-1c75-415c-8c37-e5000b202286','韦傲然',2,'17194017474','辽宁省沈阳市皇姑区蓝天家园'),('2b910dda-bc1e-4a73-949f-9b482f3c09f3','萧盈兰',2,'18675302555','山西省太原市万柏林区公元时代城'),('2df4e4ba-3e90-412f-9132-ca33c1daaecd','赵程缨',2,'13267119333','湖北省武汉市汉江区万松小区'),('2e5049d8-ffe4-4075-aff6-a3a2c593dc89','潘忻妍',2,'15838168295','海南省海口市龙华区碧桂园中央首府'),('5dec27e2-9d1b-40b7-a19b-e9d8436d9c78','汤丞昱',1,'15201363549','河北省石家庄市裕华区安苑小区'),('5e32f933-7b23-4986-a72e-3c0f83bffd0f','李明',1,'18897899098','内蒙古自治区呼和浩特市回民区万嘉康城');

2、依赖

<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.6.4</version>
</dependency>	
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.30</version>
</dependency>
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.7</version>
</dependency>
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper</artifactId>
	<version>5.2.0</version>
</dependency>

3、log4j.properties日志文件

log4j.rootLogger=debug,console,file

#输出到控制台
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n

#输出到文件
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=D:\\log4j.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n

#SQL语句
log4j.logger.com.mybatis=DEBUG
log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

4、mybatis-config.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>
	<!-- 添加mybatis分页插件 -->
	<plugins>
		<!-- com.github.pagehelper为PageHelper类所在包名 -->
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- 如果pageNum超出合法范围,是否返回正确结果 -->
			<property name="reasonable" value="true" />
			<!-- 如果pageSize传入0,是否返回所有数据(不分页) -->
			<property name="pageSizeZero" value="true" />
		</plugin>
	</plugins>

	<environments default="development">
		<!-- 配置数据库连接信息 -->
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.cj.jdbc.Driver" />
				<property name="url"
					value="jdbc:mysql://127.0.0.1:3306/test?useSSL=false" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>

	<!-- 注册Mapper xml文件 -->
	<mappers>
		<mapper resource="./sql/StudentMapper.xml" />
	</mappers>
</configuration>

5、Student类

package com.soft.vo;

public class Student {

	private String id;
	private String name;
	private int sex;
	private String mobile;
	private String address;
	
	...省略getter/setter...
    
	@Override
	public String toString() {
		return "id=" + id + ", name=" + name + ", sex=" + sex + ", mobile=" + mobile + ", address=" + address;
	}
}

6、IStudentDao接口

package com.soft.student;

import com.github.pagehelper.Page;
import com.soft.vo.Student;

public interface IStudentDao {

	Page<Student> select();
}

7、StudentMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.soft.student.IStudentDao">
	<select id="select" resultType="com.soft.vo.Student">
		select * from student
	</select>
</mapper>

8、测试

package com.soft.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.soft.student.IStudentDao;
import com.soft.vo.Student;

public class Test {

	public static void main(String[] args) throws IOException {
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			IStudentDao studentDao = openSession.getMapper(IStudentDao.class);
			// 只有紧跟在PageHelper.startPage方法后面的第一个查询会被分页
			int pageNum=2;
			int pageSize=5;
			PageHelper.startPage(pageNum, pageSize);
			Page<Student> pagination = studentDao.select();
			// 获取总记录数
			pagination.getTotal();
			// 获取总页数
			pagination.getPages();
			// 获取页面大小
			pagination.getPageSize();
			// 获取当前页码
			pagination.getPageNum();
			
			List<Student> list = pagination.getResult();
			for (Student student : list) {
				System.out.println(student);
			}
		} finally {
			//释放资源
			openSession.close();
		}
	}
}
 类似资料: