java 分頁對象以及數據庫分頁查詢


import java.util.List;

public class Pager<T> {
    
    private Integer pageSize;
    
    private Integer totalRecord;
    
    private Integer totalPage;
    
    private Integer currentPage;
    
    private List<T> list;
    
    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(Integer totalRecord) {
        this.totalRecord = totalRecord;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }


    public Pager(Integer pageNo,Integer pageSize,List<T> sourceList){
         if(sourceList==null){
             return;
         }
         
         //總記錄數
         this.totalRecord = sourceList.size();
         
         //每頁顯示多小條數據
         this.pageSize = pageSize;
         
         //總頁數
         this.totalPage = this.totalRecord % this.pageSize == 0?this.totalRecord/this.pageSize:this.totalRecord/this.pageSize+1;
         
         //當前第幾頁
         if(this.totalPage < pageNo){
             this.currentPage = this.totalPage;
         }else{
             this.currentPage = pageNo;
         }
         
         
         //起始索引 將此字段作為數據庫分頁查詢的開始索引
         Integer startIndex = this.pageSize * (this.currentPage - 1);
}

MySQL數據庫實現分頁查詢的SQL語句寫法!

一:分頁需求:

客戶端通過傳遞start(頁碼),limit(每頁顯示的條數)兩個參數去分頁查詢數據庫表中的數據,那我們知道MySql數據庫提供了分頁的函數limit m,n,但是該函數的用法和我們的需求不一樣,所以就需要我們根據實際情況去改寫適合我們自己的分頁語句,具體的分析如下:

比如:

查詢第1條到第10條的數據的sql是:select * from table limit 0,10;   ->對應我們的需求就是查詢第一頁的數據:select * from table limit (1-1)*10,10;

查詢第10條到第20條的數據的sql是:select * from table limit 10,20;  ->對應我們的需求就是查詢第二頁的數據:select * from table limit (2-1)*10,10;

查詢第20條到第30條的數據的sql是:select * from table limit 20,30;  ->對應我們的需求就是查詢第三頁的數據:select * from table limit (3-1)*10,10;

二:通過上面的分析,可以得出符合我們自己需求的分頁sql格式是:select * from table limit (currentPage-1)*limit,limit; 其中currentPage是頁碼,limit是每頁顯示的條數。


  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM