spring data jpa 动态查询
作者:互联网
@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 }
标签:Sort,attr,jpa,spring,String,StudentRepository,data,public,pageable 来源: https://www.cnblogs.com/jianpingcoding/p/14985901.html