PageHelper是一款好用的開源免費(fèi)的第三方物理分頁(yè)插件,這是一個(gè)基于MyBatis開源的分頁(yè)插件,使用非常方便,支持各種復(fù)雜的單表、多表分頁(yè)查詢,讓你在寫sql時(shí)無(wú)需考慮分頁(yè)問(wèn)題,PageHelper幫你搞定
1. 導(dǎo)入坐標(biāo)
<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> <!-- 配置分頁(yè)插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 設(shè)置數(shù)據(jù)庫(kù)類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數(shù)據(jù)庫(kù)--> <property name="helperDialect" value="mysql"/> </plugin> </plugins> </configuration>
然后在spring配置文件中加載mybatis的配置
<!-- 配置mybatis工廠,同時(shí)指定數(shù)據(jù)源,并與MyBatis完美整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動(dòng)掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" /> <!-- 加載mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean>
控制器中調(diào)用
@RequestMapping("select") public String selectStudent( @RequestParam(defaultValue = "1") Integer page , @RequestParam(defaultValue="2") Integer pageSize, Student student, Model model) { PageHelper.startPage(page,pageSize);//開始分頁(yè) List<Student> lists = studentService.selectStudent(student); PageInfo<Student> pageInfo = new PageInfo<Student>(lists);//封裝分頁(yè)數(shù)據(jù) model.addAttribute("pageInfo",pageInfo); return "studentlist"; }
studentlist視圖文件中:
<c:forEach items="${pageInfo.list }" var="list"> ${list.names } ${list.id } ${list.sex }<br> </c:forEach> <p>當(dāng)前${pageInfo.pageNum}頁(yè),共${pageInfo.pages}頁(yè),總共${pageInfo.total}條記錄</p> <c:if test="${!pageInfo.isFirstPage}"> <a href="${pageContext.request.contextPath }/student/select?page=1">第一頁(yè)</a> </c:if> <c:if test="${pageInfo.hasPreviousPage}"> <a href="${pageContext.request.contextPath }/student/select?page=${pageInfo.pageNum-1}">上一頁(yè)</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}">下一頁(yè)</a> </c:if> <c:if test="${!pageInfo.isLastPage}"> <a href="${pageContext.request.contextPath }/student/select?page=${pageInfo.pages}">末頁(yè)</a> </c:if>