日期 2020.03.29
    问题 如何实现多条动态件筛选
    如何解决 segmentfault
    使用spring data jpa实现统一的多条件查询

    repository

    1. @Repository
    2. public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
    3. }

    service

    1. // 多条件查询用户信息
    2. public Page<User> multiQueryUser(int page, int size, String name, String position) {
    3. Specification<User> spec = new Specification<User>() {
    4. @Override
    5. public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    6. List<Predicate> predicates = new ArrayList<>();
    7. predicates.add(criteriaBuilder.notEqual(root.get("authority"), User.ADMIN_AUTHORITY));
    8. if ("" != name) {
    9. // 根据姓名模糊查询
    10. predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
    11. }
    12. if ("" != position) {
    13. // 根据学位模糊查询
    14. predicates.add(criteriaBuilder.equal(root.get("position"), position));
    15. }
    16. Predicate[] arr = new Predicate[predicates.size()];
    17. return criteriaBuilder.and(predicates.toArray(arr));
    18. }
    19. };
    20. Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
    21. return userRepository.findAll(spec, pageable);
    22. }

    controller

    1. // 根据条件分页筛选用户
    2. @PostMapping("/user/query/{page}")
    3. public Map queryUser(@RequestBody QueryUserVO vo, @PathVariable int page) {
    4. Page<User> pages = userService.multiQueryUser(page, 10, vo.getName(), vo.getPosition());
    5. return Map.of("content", pages.getContent(), "total", pages.getTotalElements());
    6. }