赞
踩
mybatis的分页查询可以通过PageHelper插件实现
在数据库中我们使用分页查询的sql语句为:
select * from 表名 [where 条件] limit (page-1)*pageSize, pageSize;
page: 当前页码
pageSize: 每页显示的条数。
但是当我们使用PageHelper插件后页码什么的都不用我们计算 我们可以通过直接使用它里面的函数得到我们想要的。如:总条数 总页数 当前页面呈现的数据
使用步骤:
第一步:在pom.xml中引入依赖
<dependency>
<groupId>repMaven.com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
第二步:在conf.xml中设置PageHelper拦截器
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
注意:
第三步:在测试类(单元测试)中测试:
@Test
public void testFindAll() throws Exception{
Reader rd = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rd);
SqlSession session = factory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
//pageNum:当前页 pageSize:每页显示几条数据
PageHelper.startPage(1,2);
List<User> user = userDao.findAll();
PageInfo<User> pageInfo = new PageInfo<User>(user);
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("当前页码对应的数据:"+pageInfo.getList());
session.close();
}
数据库为:
/* Navicat Premium Data Transfer Source Server : Michinaish Source Server Type : MySQL Source Server Version : 80011 Source Host : localhost:3306 Source Schema : mybatis Target Server Type : MySQL Target Server Version : 80011 File Encoding : 65001 Date: 06/06/2022 19:16:07 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for tbl_user02 -- ---------------------------- DROP TABLE IF EXISTS `tbl_user02`; CREATE TABLE `tbl_user02` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名', `pwd` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码', `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of tbl_user02 -- ---------------------------- INSERT INTO `tbl_user02` VALUES (6, '张三', '123', 'zs@qq.com'); INSERT INTO `tbl_user02` VALUES (7, '李四', '123', 'ls@qq.com'); INSERT INTO `tbl_user02` VALUES (9, 'ac', '123', 'ac@qq.com'); INSERT INTO `tbl_user02` VALUES (10, 'bc', '123', 'bc@qq.com'); INSERT INTO `tbl_user02` VALUES (11, 'cc', '123', 'cc@qq.com'); INSERT INTO `tbl_user02` VALUES (12, 'dc', '123', 'dc@qq.com'); SET FOREIGN_KEY_CHECKS = 1;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。