利用PageHelper可以很方便地对数据库查询结果进行分页
pom.xml加入对PageHelper的引用
com.github.pagehelper
pagehelper
3.5.0
dialect=mysql
offsetAsPageNum=true
rowBoundsWithCount=true
pageSizeZero=true
reasonable=true
对于前台传来的页面请求,我们需要将其中的分页信息转换成我们需要的pageNum和pageSize
我们可以这么做,新建一个PageVo类,用来记录页码,每页条数相关信息,所有的model都要继承这个类
PageVo.java(dojo.gird传来的分页信息为start,count,我们可以这么转化下)
public class PageVo {
/** 当前页码.**/
private int pageNum;
/** 每页条数.**/
private int pageSize;
/** 起始标志.**/
private int startRow;
/**对接dojo的grid**/
private int start;
private int count;
/**
* @return the pageNum
*/
public int getPageNum() {
return count>0?start/count+1:1;
}
/**
* @param pageNum the pageNum to set
*/
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
/**
* @return the pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
* @param pageSize the pageSize to set
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* @param startRow the startRow to set
*/
public void setStartRow(int startRow) {
this.startRow = startRow;
}
/**
* @return the startRow
*/
public int getStartRow() {
return this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0;
}
/**
* @return the endRow
*/
public int getEndRow() {
return this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0);
}
public int getStart() {
return start;
}
public void setStart(int start) {this.start = start; } public int getCount() { return count; } public void setCount(int count) { this.pageSize=count; this.count = count; }}
User需要继承PageVo
public class User extends PageVo{
相应Controller测试接口
@ResponseBody
@RequestMapping(value="/selectUser",method = RequestMethod.POST)
public Map selectUser(@RequestBody User user){
Map resultMap = new HashMap();
try {
Map paramMap= BeanUtil.transBean2Map(user);
PageHelper.startPage(10, 3);
Page page = userService.selectUserByCon(paramMap);
PageUtil.makePage(resultMap, page.getResult(), page.getPageNum(), page.getPageSize(), page.getTotal());
} catch (Exception e) {
PageUtil.makePage(resultMap, null, 0, 0, 0);
resultMap.put("msg", "查询用户信息失败");
resultMap.put("code", 1);
}
return resultMap;
}
BeanUtil是一个class和map互转的工具类,可见
http://blog.csdn.net/bornonew/article/details/54575550
PageUtil是把结果转成前台需要的工具类。
UserDao
Page selectUserByCon(Map paraMap);
UserMapper.xml
Test
@Test
public void testSelectUser() throws Exception {
User user=new User();
user.setPageNum(2);
user.setPageSize(4);
userController.selectUser(user);
}
修改PageNum和PageSize会有不同的结果返回