分页插件

Mybatis-Kits 所有分页都是使用物理分页,首先我们看下分页对象 Page 的数据结构:

Page 数据结构

public class Page<T> implements Serializable {
    /** 页码,默认是第一页 */
    private int pageNo = 1;
    /** 每页显示的记录数,默认是10 */
    private int pageSize = 10;
    /** 总记录数 */
    private long totalRecord;
    /** 总页数 */
    private int totalPage;
    /** 对应的当前页记录 */
    private List<T> results;

    public Page() {}

    public Page(int pageNo, int pageSize) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
    }

    public int getPageNo() {
        return pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getStartRow() {
        int startRow = this.pageNo > 0 ? (pageNo - 1) * pageSize : 0;
        return startRow;
    }

    public int getEndRow() {
        int endRow = this.pageNo * pageSize;
        return endRow;
    }

    public List<T> getResults() {
        return results;
    }

    public Page setPageNo(int pageNo) {
        this.pageNo = pageNo;
        return this;
    }

    public Page setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    public Page setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
        if (this.totalRecord != 0) {
            this.totalPage = (int) (this.totalRecord / this.pageSize);
            if (this.totalRecord % this.pageSize != 0) {
                this.totalPage++;
            }
        }
        return this;
    }

    public Page setResults(List<T> results) {
        this.results = results;
        return this;
    }

    /* 获取下一页 */
    public int getNextPage() {
        return pageNo + 1;
    }

    /* 获取上一页 */
    public int getPrevPage() {
		if (pageNo > 1) {
			return pageNo - 1;
		} else {
			return 1;
		}
    }

}

开始使用

// 查询所有记录并分页
Page<User> page = new Page<>();
page.setPageSize(10);
page = userMapper.search(page);

for (User user : page.getResults()) {
	logger.info("结果:{}",user);
}

// 按照条件查询分页
Conditions condi = new Conditions();
condi.eq("name", "Rock");
Page<User> page = new Page<>();
page.setPageSize(10);
userMapper.searchByConditions(page, condi);
// 这里调用完之后,数据已经填充到参数 page 中了
// 所以可以不用再次赋值
for (User user : page.getResults()) {
	logger.info("结果:{}",user);
}

::: Note: 分页查询到的结果直接回写到 Page 参数中了,同时也作为方法的返回值。 :::