1、Service层
- Pageable是JPA的分页类
- PageRequest.of(page,size,Sort.Direction.DESC,“key”)方法
page即当前页。
size代表每页有几条记录第三个参数是排序字段,
Sort.Direction.DESC是倒序的意思。
最后一个参数是排序关键字,将按照这个关键字进行排序。
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeRepository employeeRepository;
@Override
public RespPageBean getEmployeeByPage(Integer page, Integer size) {
if (page != null && size != null) {
page= (page-1)*size;
}
Pageable pageable = PageRequest.of(page,size, Sort.Direction.DESC,"id");
Page<Employee> allPage = employeeRepository.findAll(pageable);
List<Employee> data = allPage.getContent();
long total = allPage.getTotalElements();
RespPageBean respPageBean = new RespPageBean();
respPageBean.setData(data);
respPageBean.setTotal(total);
return respPageBean;
}
}
public class RespPageBean {
private Long total;
private List<?> data;
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<?> getData() {
return data;
}
public void setData(List<?> data) {
this.data = data;
}
}
2、Controller层
@RestController
@RequestMapping("/system/emp")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@GetMapping("/")
public RespPageBean getEmployeeByPage(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size){
return employeeService.getEmployeeByPage(page,size);
}
}