PageHelper是一款好用的开源免费的第三方物理分页插件,这是一个基于MyBatis开源的分页插件,使用非常方便,支持各种复杂的单表、多表分页查询,让你在写sql时无需考虑分页问题,PageHelper帮你搞定
1. 导入坐标
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.11</version> </dependency>
2. 在将配置放在mybatis的配置文件中
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> <!-- 配置分页插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库--> <property name="helperDialect" value="mysql"/> </plugin> </plugins> </configuration>
然后在spring配置文件中加载mybatis的配置
<!-- 配置mybatis工厂,同时指定数据源,并与MyBatis完美整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" /> <!-- 加载mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean>
控制器中调用
@RequestMapping("select") public String selectStudent( @RequestParam(defaultValue = "1") Integer page , @RequestParam(defaultValue="2") Integer pageSize, Student student, Model model) { PageHelper.startPage(page,pageSize);//开始分页 List<Student> lists = studentService.selectStudent(student); PageInfo<Student> pageInfo = new PageInfo<Student>(lists);//封装分页数据 model.addAttribute("pageInfo",pageInfo); return "studentlist"; }
studentlist视图文件中:
<c:forEach items="${pageInfo.list }" var="list"> ${list.names } ${list.id } ${list.sex }<br> </c:forEach> <p>当前${pageInfo.pageNum}页,共${pageInfo.pages}页,总共${pageInfo.total}条记录</p> <c:if test="${!pageInfo.isFirstPage}"> <a href="${pageContext.request.contextPath }/student/select?page=1">第一页</a> </c:if> <c:if test="${pageInfo.hasPreviousPage}"> <a href="${pageContext.request.contextPath }/student/select?page=${pageInfo.pageNum-1}">上一页</a> </c:if> <c:forEach items="${pageInfo.navigatepageNums }" var="n"> <a href="${pageContext.request.contextPath }/student/select?page=${n }">${n }</a> </c:forEach> <c:if test="${pageInfo.hasNextPage}"> <a href="${pageContext.request.contextPath }/student/select?page=${pageInfo.pageNum+1}">下一页</a> </c:if> <c:if test="${!pageInfo.isLastPage}"> <a href="${pageContext.request.contextPath }/student/select?page=${pageInfo.pages}">末页</a> </c:if>