1. 程式人生 > >自定義實現資料庫的分頁查詢

自定義實現資料庫的分頁查詢

我們都知道,資料庫的分頁查詢在實際專案中廣泛應用,而且能夠實現分頁查詢的外掛有很多(像Mybatis自帶的PageHelper),最近在專案中自定義了一個分頁功能,在不適用外掛的情況下也很方便。 MySql資料庫實現分頁的核心是:limit函式: LIMIT子句可以用來限制由SELECT語句返回過來的資料數量,它有一個或兩個引數,如果給出兩個引數, 第一個引數指定返回的第一行在所有資料中的位置,從0開始(注意不是1),第二個引數指定最多返回行數。例如:

select * from table WHERE … LIMIT 10; #返回前10行
select * from table WHERE … LIMIT 0,10; #返回前10行
select * from table WHERE … LIMIT 10,20; #返回第10-20行資料

結合我自己的實踐,總結如下: 1、定義分頁實體類:(我使用了lombok外掛,不用寫get/set方法):

/**
 * @author wangjie
 * @version 2018/11/10
 * 分頁實體類
 */
@Data
public class PageVO {
    //當前頁碼,預設第一頁
    private Integer currentPageNo=1;
    //總頁數
    private Integer totalCount;
    //頁面容量
    private Integer pageSize=5;
    //上一頁
    private Integer upPageNo;
    //下一頁
    private Integer nextPageNo;
    //要前往的頁碼,預設0
    private Integer toPageNo=0;

    //設定當前頁碼
    public void setCurrentPageNo(int currentPageNo) {
        if(currentPageNo!=1){
            upPageNo=currentPageNo-1;
        }
        nextPageNo=currentPageNo+1;
        this.currentPageNo = currentPageNo;
    }

    public void setToPageNo(Integer toPageNo) {
        //新一頁
        this.toPageNo = (toPageNo-1) * pageSize ;
        //設定跳轉後當前的頁碼
        setCurrentPageNo(toPageNo);
    }

    //設定總頁數:count為查詢到的記錄總數
    public void setTotalCount(int count) {
        if (count%pageSize > 0) {
            this.totalCount = (count/pageSize)+1;
        } else {
            this.totalCount = count/pageSize;
        }
    }
}

2、UserDao和UserDao.xml:

/**
     * 查詢部落格使用者總數
     */
    Integer getAllUsersCount();

    /**
     * 檢視所有部落格使用者(分頁)
     */
    List<BlogUser> findAllUser(PageVO pageBean);

3、service層:

 /*
     * 檢視所有部落格使用者(分頁)
     */
    List<BlogUser> findAllUser(PageVO pageVO);

service實現類:

 /**
     * 檢視所有部落格使用者(分頁)
     */
    @Override
    public List<BlogUser> findAllUser(PageVO pageVO){
        return blogUserDao.findAllUser(pageVO);
    }

4、Controller層:page為從前端頁面傳來的頁碼。

/**
    * 檢視所有使用者(分頁)
    */
    @RequestMapping(value=("/findAllUsers"),method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public List<BlogUser> findAllUsers(@Param("page") Integer page){

        //設定總頁數
        PageVO pageVO=new PageVO();
        pageVO.setTotalCount(blogUserService.getAllUsersCount());
        if(page==null || page==0){
            pageVO.setToPageNo(1);
           return blogUserService.findAllUser(pageVO);
        }
        pageVO.setToPageNo(page);
        return blogUserService.findAllUser(pageVO);
    }

核心程式碼如上。 5、注意事項: 要實現分頁,重點在於如何正確地給limit函式傳遞引數,涉及到如何在分頁實體類中設定各個引數的值,只有正確理解了原理,才能很輕鬆實現分頁。