@Service public class StudentSpecService { @Autowired StudentRepository repository; public Page findByPage(Integer pageNo, Integer size, String searchField, String searchKey, String sortField) {
//定义查询条件 Specification<StudentEntity> spec = (root, criteriaQuery, criteriaBuilder) -> { Path attr = root.get(searchField); // 查询表中的该字段
//criteriaBuilder有多种方法用于和attr匹配 Predicate predicate = criteriaBuilder.equal(attr, searchKey); return predicate; };
//定义排序字段选择使用倒序 Sort sort = Sort.by(Sort.Direction.DESC, sortField);
//定义pageable对象 Pageable pageable = PageRequest.of(pageNo, size, sort); Page<StudentEntity> pages = repository.findAll(spec, pageable); return pages; } }
在执行上一步之前,需要保证StudentRepository接口实现了JpaSpecificationExecutor:
1 public interface StudentRepository extends JpaRepository<StudentEntity,String>, JpaSpecificationExecutor<StudentEntity> { 2 3 }