MySQL分页语句:LIMIT M,N
M:开始记录的索引。从0开始的
N:每次查询多少条。
每次查10条:
查第一页的:SELECT * FROM table LIMIT 0,10;
查第二页的:SELECT * FROM table LIMIT 10,10;
为了在页面更好的展示,并且为了减少内存的占用率,不是一次性将数据从数据库中查出来,而是分批次去查。一般如下图显示:
分页类Page.java:
package com.cmcc.imark.util;
import java.util.List;
public class Page {
//DAO可以查出来
private List records;//存放分页记录
//界面可以传过来
private int currentPageNum;//当前页码
//DAO可以查出来
private int totalRecords;//总记录条数
private int pageSize = 5;//每页显示的条数
//算出来:根据总记录条数来算
private int totalPage;//总页数
//算出来:根据当前页码来算
private int startIndex;//每页开始的记录的索引
//记录显示的页码
private int startPage;
private int endPage;
//用户查询分页数据的请求的URL
private String url;
public Page(int currentPageNum,int totalRecords){
this.currentPageNum = currentPageNum;
this.totalRecords = totalRecords;
//计算总页数
totalPage = totalRecords%pageSize==0?totalRecords/pageSize:(totalRecords/pageSize+1);
//计算开始记录的索引
startIndex = (currentPageNum-1)*pageSize;
//计算开始和结束页码
if(totalPage<=9){//不足9页
startPage = 1;
endPage = totalPage;
}else{
startPage = currentPageNum-4;
endPage = currentPageNum+4;
if(startPage<1){
startPage = 1;
endPage = startPage+8;
}
if(endPage>totalPage){
endPage = totalPage;
startPage = endPage-8;
}
}
}
}DAO:
public int getTotalRecord(String table) {//一般的话,不带参数
String sql = "select count(*) as count from "+table;
Map map = findFirst(sql);
Object count = null;
for(String key:map.keySet()){
count = map.get(key);
}
return Integer.parseInt(count.toString());
}
public List findPageRecords(Class className,String sql,int startIndex, int pageSize) {//一般的话,就只有startIndex及pageSize两个参数
return find(className, sql,startIndex,pageSize);
}service层代码:
public Page findPageReocords(Class className,String sql,String num,String table) {
int pageNum = 1;//默认的页码
if(num!=null&&!num.trim().equals("")){
pageNum = Integer.parseInt(num);
}
int totalRecords = pageDao.getTotalRecord(table);
Page page = new Page(pageNum, totalRecords);
//查询分页记录
List records = pageDao.findPageRecords(className,sql,page.getStartIndex(), page.getPageSize());
page.setRecords(records);
return page;
}
public Page findAll(String num) {//这是实际的业务层继承了分页的service类
String sql = "select id,prizeName from prize limit ?,?";
return findPageReocords(Prize.class,sql,num, "prize");
}
控制层:
@RequestMapping("/prizeListUi")
public String prizeListUi(Model model,String num){
System.out.println("prizeListUi");
Page page = this.prizeService.findAll(num);
page.setUrl("/prizeController/prizeListUi?");
model.addAttribute("page",page);
return "/back/prize/prizeList";
}前端页面的话,直接可以使用jstl取出page中的属性即可。