- 创建一个保存页的相关数据:
package com.xibao.ssm.po;
public class Page {
private int pageSize = 30;
private int count;
private String pageNum;
private int pageCount = 0;
private int beg;
private int end;
public void setPageInfo(String pageNum,int count ){
this.pageNum = pageNum;
this.count = count;
if(count%pageSize==0){
pageCount = count/pageSize;
}else{
pageCount = count/pageSize+1;
}
beg = (Integer.parseInt(pageNum)-1)*pageSize;
end = pageSize;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getPageNum() {
return pageNum;
}
public void setPageNum(String pageNum) {
this.pageNum = pageNum;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getBeg() {
return beg;
}
public void setBeg(int beg) {
this.beg = beg;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
- MyBatis中需要用到两个sql语句才能实现分页的功能
第一个是查询出总共有多少数据:
select count(*) from 表名
注意:这个sql语句的结果是int类型的值
第二个是进行分页查询,采用的是mysql中limit
select * from 表名 limit beg,end;
beg和end都是为int类型的值,beg是为要从第几条开始读取数据,end是总共读取多少条数据
例如:
select * from 表名 limit 0,3;
就是从第一条开始读取,总共读取3条数据
注意:beg的值是从0开始算 - Controller类进行实现分页功能
/**
* 分页
* @param pagenum
* @return
*/
@RequestMapping("/paging")
public @ResponseBody List<Cabinet> paging(String pagenum){
int count = cabinetService.selectCount();
Page page = new Page();
page.setPageInfo(pagenum, count);
List<Cabinet> cabinets = cabinetService.selectLimit(page.getBeg(), page.getEnd());
for(int i = 0;i<cabinets.size();i++){
cabinets.get(i).setPage(page);
}
return cabinets;
}