PageHelper实现分页查询

PageHelper是基于拦截器实现的myBatis分页插件

PageHelper的Github主页 : https://github.com/pagehelper/Mybatis-PageHelper

一.通过maven引入PageHelper的jar包

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

  

二.在myBatis配置文件中配置PageHelper

<plugins>
	<!-- com.github.pagehelper为PageHelper类所在包名 -->
	<plugin interceptor="com.github.pagehelper.PageInterceptor">
		<!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
		<property name="helperDialect" value="mysql"/>
	</plugin>
</plugins>

  也可以在spring中配置PageHelper,具体步骤请参考PageHelper的Github主页官方教程

三.在Controller层使用PageHelper实现分页查询

	/**
	 * 分页查询练习
	 * @param mav 
	 * @param currentPage 当前页数
	 * @return
	 */
	@RequestMapping("/pagination")
	public ModelAndView queryUsers(ModelAndView mav, Integer currentPage){
		//紧挨在查询语句前调用PageHelper的startPage(int pageNum, int pageSize)方法,否则分页查询不生效
		PageHelper.startPage(currentPage, 5);
		//查询用户
		List<User> users = ts.queryUsers();
		//用PageInfo包装List查询结果,查看PageInfo源码,了解更多
		PageInfo<User> pi = new PageInfo<User>(users);

		mav.addObject("pageInfo", pi);
		mav.setViewName("test/paginationTest");
		return mav;
	}

  

四.JSP页面的书写方法

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PageHelper分页查询</title>
</head>
<body>
	<!-- 点击查询 -->
	<a href="${pageContext.request.contextPath }/test/pagination?currentPage=1">查询</a>
	<!-- 有上一页的时候显示上一页 -->
	<c:if test="${pageInfo.hasPreviousPage }">
		<a href="${pageContext.request.contextPath }/test/pagination?currentPage=${pageInfo.prePage}">上一页</a>
	</c:if>	
	<!-- 有下一页的时候显示下一页 -->
	<c:if test="${pageInfo.hasNextPage }">
		<a href="${pageContext.request.contextPath }/test/pagination?currentPage=${pageInfo.nextPage}">下一页</a>
	</c:if>	
	<!-- 遍历查询结果 -->
	<!-- 注意! 在EL表达式中,用.list即可调用pageInfo中封装的list对象 -->
	<c:forEach items="${pageInfo.list  }" var="u" >
		<p>${u.username } + ${u.realname }</p>
	</c:forEach> 
	
	<br/>当前页:${pageInfo.pageNum }
	<br/>总页数:${pageInfo.pages }
	<br/>当前页面第一个元素在数据库中的行号:${pageInfo.startRow }
	<br/>当前页面最后一个元素在数据库中的行号:${pageInfo.endRow }
</body>
</html>

  

五.其他

重点了解PageInfo类,可以自行查阅源码

关于更详细的内容(更多的配置内容和使用方法等等),请参考PageHelper官方文档

地址 : https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

f

猜你喜欢

转载自www.cnblogs.com/jinyu59/p/10822487.html