在這裏總結使用Mybatis註解時的兩種分頁方法:根據sql語句進行分頁 和 查詢所有數據的結合,在集合中進行分頁。
1、根據sql語句進行分頁
- controller
@GetMapping("/")
public @ResponseBody String getList(@RequestParam Map<String, Object> params){
//當前頁
int page = Integer.valueOf((String)params.get("page"));
//每頁顯示的條目
int limit = Integer.valueOf((String)params.get("limit"));
//總數量
int count = empService.getCount();
int page_temp = page;
int limit_temp = limit;
//如果剩餘的不夠當前頁顯示的,就顯示剩餘的條目
if (count < page * limit) {
limit = count - (page - 1) * limit;
}
page = (page_temp - 1) * limit_temp;
List<Employee> list = empService.getEmployeeByPage(page,limit);
String jso = "{\"code\":0,\"msg\":\"\",\"count\":"+count+",\"data\":"+JSONArray.toJSONString(list)+"}";
return jso;
}
- service
//獲取總數
public int getCount(){
return empMapper.getCount();
}
//分頁查詢
public List<Employee> getEmployeeByPage(int currentIndex,int pageSize){
return empMapper.queryEmployeeByPage(currentIndex,pageSize);
}
- mapper
//查詢總數
@Select("select count(*) from employee")
int getCount();
//分頁查詢語句
@Select("select * from employee limit #{currentIndex} , #{pageSize}")
List<Employee> queryEmployeeByPage(@Param("currentIndex")int currentIndex, @Param("pageSize")int pageSize);
2、在集合中進行分頁
- controller
@GetMapping("/")
public @ResponseBody String getList(@RequestParam Map<String, Object> params){
//當前頁
int page = Integer.valueOf((String)params.get("page"));
//每頁顯示的條目
int limit = Integer.valueOf((String)params.get("limit"));
/*
* 以數組進行分頁
* */
//總條目數量
int count = empService.getCountByParams();
//總條目的集合
List<Employee> list = empService.getEmployeeListByParams();
//從第幾條數據開始
int firstIndex = (page - 1) * limit;
//到第幾條數據結束
int lastIndex = page * limit;
//如果lastIndex>count
if(lastIndex>count){
lastIndex = count;
}
list = list.subList(firstIndex, lastIndex); //直接在list中截取
String jso = "{\"code\":0,\"msg\":\"\",\"count\":"+count+",\"data\":"+JSONArray.toJSONString(list)+"}";
return jso;
}
- service
//條件查詢
public List<Employee> getEmployeeListByParams(){
return empMapper.queryEmployeeListByParams();
}
//條件查詢總數
public int getCountByParams(){
return empMapper.queryCountByParams();
}
- mapper
//查詢所有
@Select("select * from employee")
List<Employee> queryEmployeeListByParams();
//查詢總數
@Select("select count(*) from employee")
int queryCountByParams();