PageHelper实现

添加依赖:



    com.github.pagehelper
    pagehelper
    5.1.2

 pagehelper配置:

#分页插件配置
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
    returnPageInfo: check

 代码实现:

 PageHelper.startPage(pageNum, pageSize);
 List user= dpmMapper.queryUserList();
 Page dpmPage = PageUtils.page(user);

 

public static  Page startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
        Page page = new Page(pageNum, pageSize, count);
        page.setReasonable(reasonable);
        page.setPageSizeZero(pageSizeZero);
        Page oldPage = getLocalPage();
        if (oldPage != null && oldPage.isOrderByOnly()) {
            page.setOrderBy(oldPage.getOrderBy());
        }

        setLocalPage(page);
        return page;
    }
public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

 

 PageHelper将参数保存到page对象中,接着将page的副本存放入ThreadLoacl中,这样可以保证分页的时候,参数互不影响,接着利用了mybatis提供的拦截器,取得ThreadLocal的值,重新拼装分页SQL,完成分页

public class PageUtils implements Serializable {
	private static final long serialVersionUID = 7381468955316253104L;

	public static  Page page(List list){
		Page page = new Page(list);
		return page;
	}
}
public class Page implements Serializable {
	
	private static final long serialVersionUID = 6094186219831724663L;
	private List content = new ArrayList<>(); //对象记录结果集
	private long totalPages = 0;  //总页数
	private long totalElements; //总记录数
	private int number;  //当前页
	private int size; //每页显示记录数
	private int numberOfElements; //每页显示实际记录数

	public Page(List temp) {
		com.github.pagehelper.Page result = (com.github.pagehelper.Page) temp;
		if(result != null && result.size() > 0){
			this.content = result.getResult();
			this.totalPages = result.getPages();
			this.totalElements = result.getTotal();
			this.number = result.getPageNum();
			this.size = result.getPageSize();
			this.numberOfElements = this.content.size();
		}
	}
	public Page() {
		super();
	}
}

 

你可能感兴趣的:(PageHelper实现)