1.插件寫法
MyBatis 分頁插件 - PageHelper
官網:https://gitee.com/free/Mybatis_PageHelper/
使用方法:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
首先導入Maven依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>最新版本</version>
</dependency>
在Mybatis的xml中導入 ,並修改<property name="properties">
中的value
改爲helperDialect
<bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 這是插件的配置 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!-- 注意!"""""""使用下面的方式配置參數,一行配置一個 -->
<!--Dialect 是方言 mysql 使用limit 每種數據庫不一樣-->
<value>
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
分頁插件參數介紹(需要詳細瞭解的再看)
分頁插件提供了多個可選參數,這些參數使用時,按照上面兩種配置方式中的示例配置即可。
分頁插件可選參數如下:
dialect:默認情況下會使用 PageHelper 方式進行分頁,如果想要實現自己的分頁邏輯,可以實現 Dialect(com.github.pagehelper.Dialect) 接口,然後配置該屬性爲實現類的全限定名稱。
下面幾個參數都是針對默認 dialect 情況下的參數。使用自定義 dialect 實現時,下面的參數沒有任何作用。
helperDialect:分頁插件會自動檢測當前的數據庫鏈接,自動選擇合適的分頁方式。 你可以配置helperDialect屬性來指定分頁插件使用哪種方言。配置時,可以使用下面的縮寫值:
oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby
特別注意:使用 SqlServer2012 數據庫時,需要手動指定爲 sqlserver2012,否則會使用 SqlServer2005 的方式進行分頁。
你也可以實現 AbstractHelperDialect,然後配置該屬性爲實現類的全限定名稱即可使用自定義的實現方法。
offsetAsPageNum:默認值爲 false,該參數對使用 RowBounds 作爲分頁參數時有效。 當該參數設置爲 true 時,會將 RowBounds 中的 offset 參數當成 pageNum 使用,可以用頁碼和頁面大小兩個參數進行分頁。
rowBoundsWithCount:默認值爲false,該參數對使用 RowBounds 作爲分頁參數時有效。 當該參數設置爲true時,使用 RowBounds 分頁會進行 count 查詢。
pageSizeZero:默認值爲 false,當該參數設置爲 true 時,如果 pageSize=0 或者 RowBounds.limit = 0 就會查詢出全部的結果(相當於沒有執行分頁查詢,但是返回結果仍然是 Page 類型)。
reasonable:分頁合理化參數,默認值爲false。當該參數設置爲 true 時,pageNum<=0 時會查詢第一頁, pageNum>pages(超過總數時),會查詢最後一頁。默認false 時,直接根據參數進行查詢。
params:爲了支持startPage(Object params)方法,增加了該參數來配置參數映射,用於從對象中根據屬性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值, 默認值爲pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero。
supportMethodsArguments:支持通過 Mapper 接口參數來傳遞分頁參數,默認值false,分頁插件會從查詢方法的參數值中,自動根據上面 params 配置的字段中取值,查找到合適的值時就會自動分頁。 使用方法可以參考測試代碼中的 com.github.pagehelper.test.basic 包下的 ArgumentsMapTest 和 ArgumentsObjTest。
autoRuntimeDialect:默認值爲 false。設置爲 true 時,允許在運行時根據多數據源自動識別對應方言的分頁 (不支持自動選擇sqlserver2012,只能使用sqlserver),用法和注意事項參考下面的場景五。
closeConn:默認值爲 true。當使用運行時動態數據源或沒有設置 helperDialect 屬性自動獲取數據庫類型時,會自動獲取一個數據庫連接, 通過該屬性來設置是否關閉獲取的這個連接,默認true關閉,設置爲 false 後,不會關閉獲取的連接,這個參數的設置要根據自己選擇的數據源來決定。
aggregateFunctions(5.1.5+):默認爲所有常見數據庫的聚合函數,允許手動添加聚合函數(影響行數),所有以聚合函數開頭的函數,在進行 count 轉換時,會套一層。其他函數和列會被替換爲 count(0),其中count列可以自己配置。
重要提示:
當 offsetAsPageNum=false 的時候,由於 PageNum 問題,RowBounds查詢的時候 reasonable 會強制爲 false。使用 PageHelper.startPage 方法不受影響。
PageHelper.startPage 靜態方法調用
還有一種的是侵入式調用RowBounds方式的調用,我們用第一種,原理是動態代理
在service使用
@Override
public PageInfo findAll(Integer page,Integer size) {
//開始使用分頁
PageHelper.startPage(page,size);
List<Company> all = companyDao.findAll();
//使用pageInfo接受 Mybatis知道
PageInfo pageInfo = new PageInfo(all);
return pageInfo;
}
在Contorller使用
@RequestMapping(value = "/list",name = "顯示所有公司列表")
public String list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5")Integer size){
PageInfo all = companyService.findAll(page, size);
request.setAttribute("page",all);
return "company/company-list";
}
前端分頁欄
分頁欄代碼:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<div class="pull-left">
<div class="form-group form-inline">
總共${page.pages} 頁,共${page.total} 條數據。
<select id="selectSize" onchange="showSelection(this.options[this.options.selectedIndex].value)" class="form-control">
<option ${page.size eq 5 ? 'selected="selected"' : ""}>5</option>
<option ${page.size eq 10 ? 'selected="selected"' : ""}>10</option>
<option ${page.size eq 20 ? 'selected="selected"' : ""}>20</option>
<option ${page.size eq 40 ? 'selected="selected"' : ""}>40</option>
</select> 條
</div>
</div>
<div class="box-tools pull-right">
<ul class="pagination" style="margin: 0px;">
<li >
<a href="javascript:goPage(1)" aria-label="Previous">首頁</a>
</li>
<li><a href="javascript:goPage(${page.prePage})">上一頁</a></li>
<c:forEach begin="${page.navigateFirstPage}" end="${page.navigateLastPage}" var="i">
<li class="paginate_button ${page.pageNum==i ? 'active':''}"><a href="javascript:goPage(${i})">${i}</a></li>
</c:forEach>
<li><a href="javascript:goPage(${page.nextPage})">下一頁</a></li>
<li>
<a href="javascript:goPage(${page.pages})" aria-label="Next">尾頁</a>
</li>
</ul>
</div>
<form id="pageForm" action="${param.pageUrl}" method="post">
<input type="hidden" name="page" id="pageNum">
<input type="hidden" name="PageSize" id="pageSize"value="${page.pageSize}">
</form>
<script>
function showSelection(selection){
document.getElementById("pageSize").value=selection;
goPage(1);
}
function goPage(page) {
document.getElementById("pageNum").value = page
var select=document.getElementById("selectSize")
var selectValue=select.options[select.options.selectedIndex].value
document.getElementById("pageSize").value = selectValue
document.getElementById("pageForm").submit()
}
</script>
</body>
</html>
將分頁欄引入其他頁面 並 傳遞表單action的 value
<!-- .box-footer-->
<div class="box-footer">
<jsp:include page="../common/pageMybatis.jsp">
<jsp:param name="pageUrl" value="${ctx}/system/dept/list.do" />
</jsp:include>
</div>
PageInfo屬性介紹
public class PageInfo<T> implements Serializable {
private static final long serialVersionUID = 1L;
//當前頁
private int pageNum;
//每頁的數量
private int pageSize;
//當前頁的數量
private int size;
//由於startRow和endRow不常用,這裏說個具體的用法
//可以在頁面中"顯示startRow到endRow 共size條數據"
//當前頁面第一個元素在數據庫中的行號
private int startRow;
//當前頁面最後一個元素在數據庫中的行號
private int endRow;
//總記錄數
private long total;
//總頁數
private int pages;
//結果集
private List<T> list;
//前一頁
private int prePage;
//下一頁
private int nextPage;
//是否爲第一頁
private boolean isFirstPage = false;
//是否爲最後一頁
private boolean isLastPage = false;
//是否有前一頁
private boolean hasPreviousPage = false;
//是否有下一頁
private boolean hasNextPage = false;
//導航頁碼數
private int navigatePages;
//所有導航頁號
private int[] navigatepageNums;
//導航條上的第一頁
private int navigateFirstPage;
//導航條上的最後一頁
private int navigateLastPage;
public PageInfo() {
}
2.原生寫法
構建PageBean類
package com.czh.web.PageBean;
import java.util.List;
public class PageInfo {
private Integer pageNumber;
private Integer pageSize;
private Integer startIndex;
private Integer totalPages;
private Long totalRecord;
private List list;
private Integer start;
private Integer end;
public PageInfo(Integer pageNumber,Integer pageSize,Long totalRecord,List list){
this.totalRecord=totalRecord;
this.totalPages = (int) (totalRecord%pageSize==0 ? (totalRecord/pageSize) : (totalRecord/pageSize+1));
this.list = list;
this.pageNumber=pageNumber;
this.pageSize=pageSize;
this.startIndex = (pageNumber - 1) * pageSize;
jisuan();
}
@Override
public String toString() {
return "PageInfo{" +
"pageNumber=" + pageNumber +
", pageSize=" + pageSize +
", startIndex=" + startIndex +
", totalPages=" + totalPages +
", totalRecord=" + totalRecord +
", list=" + list +
", start=" + start +
", end=" + end +
'}';
}
public void jisuan(){
if(totalPages<10){
start=1;
end=totalPages;
}else{
if(pageNumber<=10){
start=1;
end=10;
}else{
if(pageNumber==totalPages){
end = totalPages;
start =totalPages-9;
return;
}
start=pageNumber-4;
end=pageNumber+5;
}
}
}
public Integer getPageNumber() {
return pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getStartIndex() {
return startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}
public Integer getTotalPages() {
return totalPages;
}
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
public Long getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(Long totalRecord) {
this.totalRecord = totalRecord;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
}
Contorller使用
@RequestMapping(value = "/list",name = "根據公司id,查詢部門列表")
public String list(@RequestParam(defaultValue = "1") String id,@RequestParam(defaultValue = "1") Integer PageNumber,@RequestParam(defaultValue = "5") Integer PageSize){
System.out.println("頁數:"+PageNumber);
//設置totalRecord
Long count=departmentService.findPageRecord(id);
//分頁查詢數據
List<Dept> all = departmentService.findPagelist(id,(PageNumber-1)*PageSize,PageSize);
System.out.println(all);
System.out.println("總數:"+count);
PageInfo pageInfo = new PageInfo(PageNumber,PageSize,count,all);
System.out.println(pageInfo);
request.setAttribute("page",pageInfo);
return "system/dept/dept-list";
}
Service使用
@Override
public List<Dept> findPagelist(String companyId, Integer startIndex, Integer PageSize) {
return departmentDao.findPagelist(companyId,startIndex,PageSize);
}
前端page.jsp使用
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<div class="pull-left">
<div class="pull-left">
<div class="form-group form-inline">
總共${page.totalPages} 頁,共${page.totalRecord} 條數據。
<select id="selectSize" onchange="showSelection(this.options[this.options.selectedIndex].value)" class="form-control">
<option ${page.pageSize eq 5 ? 'selected="selected"' : ""}>5</option>
<option ${page.pageSize eq 10 ? 'selected="selected"' : ""}>10</option>
<option ${page.pageSize eq 20 ? 'selected="selected"' : ""}>20</option>
<option ${page.pageSize eq 40 ? 'selected="selected"' : ""}>40</option>
</select> 條
</div>
</div>
</div>
<div class="box-tools pull-right">
<ul class="pagination" style="margin: 0px;">
<li >
<a href="javascript:goPage(1)" aria-label="Previous">首頁</a>
</li>
<li><a href="javascript:goPage(${page.pageNumber eq 1 ? 1 : page.pageNumber+1 })">上一頁</a></li>
<c:forEach begin="${page.start}" end="${page.end}" var="i">
<li class="paginate_button ${page.pageNumber==i ? 'active':''}"><a href="javascript:goPage(${i})">${i}</a></li>
</c:forEach>
<li><a href="javascript:goPage(${page.pageNumber eq page.totalPages ? page.totalPages : page.pageNumber+ 1})">下一頁</a></li>
<li>
<a href="javascript:goPage(${page.totalPages})" aria-label="Next">尾頁</a>
</li>
</ul>
</div>
<form id="pageForm" action="${param.pageUrl}" method="post">
<input type="hidden" name="PageNumber" id="pageNum">
<input type="hidden" name="PageSize" id="pageSize"value="${page.pageSize}">
</form>
<script>
function showSelection(selection){
document.getElementById("pageSize").value=selection;
goPage(1);
}
function goPage(page) {
document.getElementById("pageNum").value = page
var select=document.getElementById("selectSize")
var selectValue=select.options[select.options.selectedIndex].value
document.getElementById("pageSize").value = selectValue
document.getElementById("pageForm").submit()
}
</script>
</body>
</html>
在其他頁面引入該頁面 傳遞action的 value
<div class="box-footer">
<jsp:include page="../../common/page.jsp">
<jsp:param name="pageUrl" value="${ctx}/system/dept/list.do" />
</jsp:include>
</div>
來自一位大佬的pageResult (僅供參考)
package cn.itcast.common.entity;
import java.io.Serializable;
import java.util.List;
/**
* 分頁結果類
* @author Administrator
*
*/
public class PageResult implements Serializable {
private long total;//總記錄數
private List rows;//當前頁記錄
private int page;
private int size;
private int totalPage;
private int beg;
private int end;
private int pre;
private int next;
private static int DEFAULT_PAGE_RANGE=4;
public PageResult(){}
public PageResult(long total, List rows, int page, int size) {
super();
this.total = total;
this.rows = rows;
this.page = page;
this.size = size;
// 計算
this.totalPage = (int) (total % size == 0 ? (total/size): (total/size+1));
// 獲取顯示起始頁碼
calcPage(page,totalPage,2);
this.pre = page == 1 ? 1: page-1;
this.next = page == totalPage ? totalPage:page+1;
}
public void calcPage(int pageNum,int pageCount,int sideNum){
int startNum = 0;
int endNum = 0;
if(pageCount<=sideNum){
endNum = pageCount;
}else{
if((sideNum+pageNum)>=pageCount){
endNum = pageCount;
}else{
endNum = sideNum+pageNum;
if((sideNum+pageNum)<=(2*sideNum+1)){
if((2*sideNum+1)>=pageCount){
endNum = pageCount;
}else{
endNum = 2*sideNum+1;
}
}else{
endNum = sideNum + pageNum;
}
}
}
if(pageNum<=sideNum){
startNum = 1;
}else{
if((pageNum+sideNum)>=pageCount){
if((2*sideNum+1)>=pageCount){
if((pageCount - 2*sideNum)>=1){
startNum = pageCount - 2*sideNum;
}else{
startNum = 1;
}
}else{
startNum = pageCount - 2*sideNum;
}
}else{
if((pageNum-sideNum)>=1){
startNum = pageNum - sideNum;
}else{
startNum = 1;
}
}
}
this.beg = startNum;
this.end = endNum;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getBeg() {
return beg;
}
public void setBeg(int beg) {
this.beg = beg;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getPre() {
return pre;
}
public void setPre(int pre) {
this.pre = pre;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
}