基于Mybatis分页插件PageHelper使用

前言

本文主要如何使用Mybatis分页插件PageHelper更加有效率的开发出一个具有分页的表单数据,免去人工自己写分页条件,并且在PageHelper中有很多分页之后的属性,比如当前页码,总页码,总记录数等等

操作步骤

1.使用maven自动化构建工具,在pom.xml中导入PageHelper的坐标:

javascript 复制代码
	<!--分页Pagehelper插件 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.0.0</version>
		</dependency>

2.注意这一步很重要,可能已经写好mapper的sql语句,controller,service都写好了,准备测试,但是如果这一步没有配置,PageHelper是不会起作用的,这一步就是在mybatis的配置文件中,配置使用PageHelper插件:

javascript 复制代码
<!-- 引入分页查询的插件 -->
  	 <!-- com.github.pagehelper为PageHelper类所在包名 -->
  	<plugins>
  		<plugin interceptor="com.github.pagehelper.PageInterceptor">
  		<!--分页合理化,没有前一页的时候,赋为1  -->
  		<property name="reasonable" value="true"></property>
  		</plugin>
  	</plugins>

3.测试pagehelper组件,编写controller类,查询方法之前调用PageHelper.startPage()方法来设置分页参数。然后,执行你的查询方法,MyBatis会自动为你添加分页SQL。注意PageHelper.startPage()方法应该在查询方法之前调用,并且只对紧跟其后的第一个查询有效。因此,你应该在调用startPage()之后立即执行你的查询方法。 在Controller类中,调用PageHelper.startPage()方法设置分页参数,然后执行查询方法。例如:

javascript 复制代码
	@RequestMapping("/getStudents")
	@ResponseBody
	public Msg getAllStudents(@RequestParam(value="pn",defaultValue="1")int pn){
		

		//引入PageHelper分页插件
		//在查询之前只需调用,传入页码pageNum,以及每页的大小pageSize(显示条目)
		PageHelper.startPage(pn, 10);
		List<Student> students = studentService.selectAll();
		//使用PageInfo包装查询后的结果,只需要pageInfo交给页面就行
		//封装了详细的分页信息,包括我们查询出来的数据,传入连续显示的页数
		PageInfo page =new PageInfo(students,5);
		System.out.println("当前页码1111:"+page.getPageNum());
		System.out.println("总页码11111:"+page.getPages());
		//运用链示写法,将获取的信息放在Msg的extend中
		return Msg.success().add("studentInfo", page);
		
	}

4.进行单元测试,模拟请求并验证分页结果,主要利用MockMvc在测试类中,模拟请求MVC模式,如下代码:

javascript 复制代码
package com.webapp.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.github.pagehelper.PageInfo;
import com.webapp.bean.Student;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
public class TestMvc {

	
	//传入springMVC的ioc
		@Autowired
		WebApplicationContext context;
		//虚拟MVC请求,获取到处理结果
		MockMvc mockMvc;
		
		@Before
		public void initMokcMvc(){
			//模拟请求拿到返回值
			mockMvc=MockMvcBuilders.webAppContextSetup(context).build();
		}
		
		@Test
		public void testPage() throws Exception{
			//模拟请求拿到返回值
			MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/main/getStudents").param("pn", "2")).andReturn();
			
			//请求成功以后,请求域中会有pageInfo,我们可以取出pageInfo进行验证
			MockHttpServletRequest request=result.getRequest();
			PageInfo pageInfo = (PageInfo) request.getAttribute("studentInfo");
			System.out.println("当前页码:"+pageInfo.getPageNum());
			System.out.println("总页码:"+pageInfo.getPages());
			System.out.println("总记录数:"+pageInfo.getTotal());
			System.out.println("在页面需要连续显示的页码:");
			int[] nums=pageInfo.getNavigatepageNums();
			for (int i :nums) {
				System.out.println(" "+i);
			}
			
			//获取员工数据
			List<Student> list = pageInfo.getList();
			for (Student student : list) {
				System.out.println("ID"+student.getStuId()+"==>name:"+student.getStuName());
			}
		}
		
}

5.通过上述操作步骤,接下来就继续测试,实际接口调用获取结果输出值,如图所示

总结

本文主要介绍了如何使用Mybatis分页插件PageHelper进行分页查询,以提高开发效率。文章首先强调了分页插件的重要性,然后详细介绍了配置和使用PageHelper的步骤,并通过示例代码展示了如何在Controller中进行分页查询以及如何对分页结果进行单元测试。最后,文章通过实际接口调用的方式验证了分页效果。

相关推荐
Rust研习社3 分钟前
深入 Rust 引用计数智能指针:Rc 与 Arc 从入门到实战
开发语言·后端·rust
树獭叔叔9 分钟前
OpenCLI:让任何网站成为你的命令行工具
后端·aigc·openai
峥嵘life21 分钟前
Android + Kiro AI软件开发实战教程
android·后端·学习
石榴树下的七彩鱼1 小时前
Python OCR 文字识别 API 接入完整教程
开发语言·人工智能·后端·python·ocr·api·图片识别
Memory_荒年1 小时前
别让用户“剁手”把你搞破产:接口幂等性与防重的终极防线
后端
掘金者阿豪1 小时前
程序员必踩的一个坑:Codex 报错 Missing environment variable `OPENAI_API_KEY`,完整解决指南(附架构图)
后端
神奇小汤圆2 小时前
从分析 Claude Code 源码到自己写一个:AnyCoder,支持 DeepSeek/Qwen 等任意大模型的开源 AI 编程 Agent
后端
悟空码字2 小时前
别再重复造轮子了!SpringBoot对接第三方系统模板,拿来即用
java·spring boot·后端
程序员cxuan2 小时前
为什么 Claude 要求实名认证?
人工智能·后端·程序员
Lsk_Smion2 小时前
Hot100(开刷) 之 环形链表(II)-- 随机链表的复制 -- 翻转二叉树
java·后端·kotlin·力扣·hot100