实体类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);
PageBean pageBean = empService.page(page,pageSize);
return Result.success(pageBean);
}
}
public interface EmpMapper {
// 查询记录数
@Select("select count(*) from tlias.emp")
public Long count();
@Select("select * from tlias.emp limit #{start},#{pageSize}")
public List<Emp> page(Integer start,Integer pageSize);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageBean {
// 总记录数
private Long total;
// 结果列表
private List rows;
}
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) {
Long count = empMapper.count();
Integer start = (page - 1) * pageSize;
List<Emp> empList = empMapper.page(start,pageSize);
PageBean pageBean = new PageBean(count,empList);
return pageBean;
}
}
简化
分页插件PageHepler
注入依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
@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);
PageBean pageBean = empService.page(page,pageSize);
return Result.success(pageBean);
}
}
public PageBean page(Integer page, Integer pageSize) {
PageHelper.startPage(page,pageSize);
List<Emp> empList = empMapper.list();
Page<Emp> p = (Page<Emp>) empList;
PageBean pageBean = new PageBean(p.getTotal(),p.getResult());
return pageBean;
}
public interface EmpService {
PageBean page(Integer page, Integer pageSize);
}
@Mapper
public interface EmpMapper {
// 查询记录数
// @Select("select count(*) from tlias.emp")
// public Long count();
//
// @Select("select * from tlias.emp limit #{start},#{pageSize}")
// public List<Emp> page(Integer start,Integer pageSize);
@Select("select * from tlias.emp")
public List<Emp> list();
}