这是表结构:
-- 推导一个公式
-- select * from emp
-- order by empno
-- limit 每页显示记录数 * (第几页-1),每页显示记录数
select count(*) from emp;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Integer code;// 响应码: 1代表成功 0 代表失败
private String mes; // 响应信息 描述字符串
private Object date; // 返回的数据
public static Result success(){
return new Result(1, "success", null);
}
public static Result success(Object date){
return new Result(1, "success", date);
}
public static Result error(String msg){
return new Result(0, msg, null);
}
}
@Mapper
public interface EmpMapper {
@Select("select count(*) from emp")
public long count();
@Select("select * from emp limit #{start},#{pageSize}")
public List page(Integer start,Integer pageSize);
}
public interface EmpService {
Pagebean page(Integer page, Integer pageSize);
}
@Service
public class EmpServiceImpl implements EmpService{
@Autowired
private EmpMapper empMapper;
@Override
public Pagebean page(Integer page, Integer pageSize) {
//1.获取总记录数
Long count = empMapper.count();
//2.获取分页查询结果列表
Integer start = (page-1)*pageSize;
List empList = empMapper.page(start,pageSize);
//3.封装pageBean对象
Pagebean pageBean = new Pagebean(count, empList);
return pageBean;
}
}
@Slf4j
@RestController
public class EmpController {
@Autowired
private EmpService empService;
@GetMapping("/emps")
public Result page(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer pageSize){
log.info("分页查询,参数: {},{}", page,pageSize);
//调用service分页查询
Pagebean pagebean = empService.page(page,pageSize);
return Result.success(pagebean);
}
}
完结,在postman测试成功!
com.github.pagehelper
pagehelper-spring-boot-starter
1.4.2
@Mapper
public interface EmpMapper {
@Select("select * from emp")
public List list();
}
public interface EmpService {
Pagebean page(Integer page, Integer pageSize);
}
4.实现Service服务类:
@Service
public class EmpServiceImpl implements EmpService{
@Autowired
private EmpMapper empMapper;
@Override
public Pagebean page(Integer page, Integer pageSize) {
//1.设置分页参数
PageHelper.startPage(page, pageSize);
//2.执行查询
List empList = empMapper.list();
Page p = (Page) empList;
//3.封装pageBean对象
Pagebean pageBean = new Pagebean(p.getTotal(), p.getResult());
return pageBean;
}
}
@Slf4j
@RestController
public class EmpController {
@Autowired
private EmpService empService;
@GetMapping("/emps")
public Result page(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer pageSize){
// if(page == null){
// page = 1;
// }
// if(pageSize == null) {
// pageSize = 10;
// }
log.info("分页查询,参数: {},{}", page,pageSize);
//调用service分页查询
Pagebean pagebean = empService.page(page,pageSize);
return Result.success(pagebean);
}
}
自行进行测试,完结散花!