日期 | 2020.03.29 |
---|---|
问题 | 如何实现多条动态件筛选 |
如何解决 | segmentfault 使用spring data jpa实现统一的多条件查询 |
repository
@Repository
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
}
service
// 多条件查询用户信息
public Page<User> multiQueryUser(int page, int size, String name, String position) {
Specification<User> spec = new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
predicates.add(criteriaBuilder.notEqual(root.get("authority"), User.ADMIN_AUTHORITY));
if ("" != name) {
// 根据姓名模糊查询
predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
}
if ("" != position) {
// 根据学位模糊查询
predicates.add(criteriaBuilder.equal(root.get("position"), position));
}
Predicate[] arr = new Predicate[predicates.size()];
return criteriaBuilder.and(predicates.toArray(arr));
}
};
Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
return userRepository.findAll(spec, pageable);
}
controller
// 根据条件分页筛选用户
@PostMapping("/user/query/{page}")
public Map queryUser(@RequestBody QueryUserVO vo, @PathVariable int page) {
Page<User> pages = userService.multiQueryUser(page, 10, vo.getName(), vo.getPosition());
return Map.of("content", pages.getContent(), "total", pages.getTotalElements());
}