原理:通过拦截器,在mybatis执行sql语句前,对sql语句进行处理,最后获得所需的所有分页数据。
步骤:
1.需要创建四个类:PageData,PageNav,PageRequest,PageInterceptor,ReflectHelper
2.其作用:
PageData:用于包含分页的所有信息
PageNav:分页导航信息
PageRequest:分页请求对象,用于进行分页时传入的参数
PageInterceptor:分页用到的拦截器
ReflectHelper:用于反射执行的对象或方法。
3.用法:
1)配置拦截器:
<configuration>
<plugins>
<plugin interceptor="拦截器包路径">
<property name="dialect" value="mysql(指对应的数据库类型)" />
<property name="pageSqlId" value=".*page(拦截器拦截的规则,要求执行的sql方法要以page结尾)" />
</plugin>
</plugins>
</configuration>
2)mybatis的sql类型中的select元素中id的值要以page结尾
<select id="hahapage" resultMap="BaseResultMap">
select * from user
</select>
3.代码如下:
PageData代码:
public class PageData<T> {
protected final int pageSize;
protected final int firstIndex;
protected final int lastIndex;
protected final List<T> items;
protected final int totalItems;
protected final int totalPages;
protected int currentPage;
protected final int pageItemsCount;
public int getPageSize() {
return this.pageSize;
}
public int getFirstIndex() {
return this.firstIndex;
}
public int getLastIndex() {
return this.lastIndex;
}
public List<T> getItems() {
return this.items;
}
public int getTotalItems() {
return this.totalItems;
}
public int getTotalPages() {
return this.totalPages;
}
public int getCurrentPage() {
return this.currentPage;
}
public int getPageItemsCount() {
return this.pageItemsCount;
}
public PageData() {
this(1, 0, PageRequest.defaultPageSize, (List) null);
}
public PageData(int page, int size) {
this(page, size, PageRequest.defaultPageSize, (List) null);
}
public PageData(int page, int size, int pageSize) {
this(page, size, pageSize, (List) null);
}
public PageData(PageRequest req, int size, List<T> items) {
this(req.getPage(), size, req.getSize(), items);
}
public PageData(int page, int size, int pageSize, List<T> items) {
if (pageSize <= 0) {
pageSize = PageRequest.defaultPageSize;
}
this.pageSize = pageSize;
this.totalItems = size;
this.items = items;
this.totalPages = this.totalItems % pageSize == 0 ? this.totalItems / pageSize : this.totalItems / pageSize + 1;
if (page < 1) {
page = 1;
}
if (page > this.totalPages) {
page = this.totalPages;
}
this.currentPage = page;
this.firstIndex = calcFirstItemIndexOfPage(page, pageSize, size);
int last = this.isLastPage() ? this.totalItems - 1 : this.firstIndex + pageSize - 1;
int itemsPerPage = last - this.firstIndex + 1;
if (last < 0) {