使用Pageable 分页
1. service层 封装
package com.example.demo.service; import java.util.List; import org.springframework.data.domain.Pageable; public abstract class Page<T> { private Integer page;//页数 private Integer size;//每页数量 private Number total;//总数 private List<T> content; public Page(Pageable pageable) { total = count(); page = pageable.getPageNumber(); size = pageable.getPageSize(); if(page <= 0) { page = 1; } long end = (long)page*size; long start = end - size; content = search(start , end); } /** * 获取总数 */ protected abstract Number count(); /** * 查询结果 */ protected List<T> search(Long start , Long end){ return null; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public List<T> getContent() { return content; } public void setContent(List<T> content) { this.content = content; } }
2.控制层@PageableDefault 的使用: @PageableDefault Pageable pagealbe
传递参数的时候 , 需要传递page(当前页数,没有的话默认为1),size(每页数据记录数,没有的话默认为10);
3.eg service层 , 查询Student
Page<Student> getStudentList(Pageable pageable ,Long start , Long end);
ServiceImpl
Page<Student> getStudentList(Pageable pageable , Long start , Long end){
return new Page<Student>{
@Override
protected Number count() {
return studentMapper.count();
}
@Override
protected List<Student> search(Long start, Long end){
return studentMapper.list(start , end);
}
}
}
温故而知新