Hibernate 同时使用分页、排序、筛选

在没有复杂查询的时候使用 Example 即可实现,在接口上需继承 JpaRepository<User, Integer>

// 筛选
User user = new User();
user.setCity(city);
Example<User> userExample = Example.of(user);

// 排序
Sort sort = new Sort(Sort.Direction.DESC, "createdAt");
// 分页
Pageable pageable = PageRequest.of(currentPage - 1, size, sort);
// 取得数据
Page<User> pageHelper = userRepository.findAll(example, pageable);

如果有 where in 等复杂查询时,Example 无法实现相关功能,只能用 Specification 实现,在接口上还需继承 JpaSpecificationExecutor<User>

Specification<User> specification = (Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
    List<Predicate> list = new ArrayList<>();
    if (city != null) {
        list.add(root.get("city").as(Integer.class).in((Object[]) city.split(","))); // where in
        // list.add(criteriaBuilder.equal(root.get("city").as(Integer.class), city)); // 精确查找
    }
    Predicate[] predicates = new Predicate[list.size()];
    criteriaQuery.where(criteriaBuilder.and(list.toArray(predicates)));
    return criteriaQuery.getRestriction();
};

// 省略部分代码
List<User> list = userRepository.findAll(specification, pageable);

这里使用了 Lambda 表达式,这篇只简单介绍了一下相关功能的实现,更多请自行探索。

猜你喜欢

转载自www.cnblogs.com/StarUDream/p/9045552.html