【问题标题】:Get JPAQuery results as a Page以页面形式获取 JPAQuery 结果
【发布时间】:2019-07-08 17:28:13
【问题描述】:

我有一个无法转换为 spring findBy... 查询的 JPAQuery。我设法只获得了使用offsetlimit 请求的少量结果。问题是,为了对结果进行实际分页,我需要与使用 spring 存储库方法获得的相同数据(结果总数和 nb 页)。我的代码现在看起来像这样:

public List<Long> findByCountryId(Long countryId, Pageable pageable) {
    JPAQuery<Long> query = new JPAQuery<>(this.entityManager);
    // innerJoins, where, ...
    query
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize());
    return query.fetch();
}

我曾想过自己构建页面,但我想我必须请求整个结果集而不是获取少于 50 行的数据,并且我可以从这个查询中获得数千个结果。

有没有从 JPAQuery 获取页面的干净方法?

【问题讨论】:

    标签: java spring-boot jpa pagination spring-data-jpa


    【解决方案1】:

    这就是 JPA 中的分页功能。首先需要有关行数的信息来检查您的偏移量是否不超过数据,然后如果可能的话对数据运行实际查询,否则会引发异常。

    【讨论】:

    • 我作为临时解决方案所做的是我使用query.fetchCount() 来获取总行数,然后我添加offsetlimit(没有检查偏移量是否根据行的 nb 是正确的)我再次使用fetch() 运行查询。如果我明白你在说什么,这就是 JPA 会做的,因此,这是一个干净的解决方案?
    • 是的,它们是等价的
    【解决方案2】:

    在规范的帮助下,我可能会更容易实现,但我不知道,因为我有点不确定你真正需要什么。无论如何,请参阅以下存储库、关于它的规范,尤其是它实现的接口:

    public interface SomeEntityRepository extends Repository<SomeEntity, Long>,
        PagingAndSortingRepository<SomeEntity, Long>, JpaSpecificationExecutor<SomeEntity> {
    
        @SuppressWarnings("serial")
        public static Specification<SomeEntity> findByCountryIdSpecification(Long countryId) {
            return new Specification<SomeEntity>() {
                @Override
                public Predicate toPredicate(Root<SomeEntity> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                    // implement query logic with "countryId" here
                    return null;
                }
            };
        }
    //  there will be a method like below with JpaSpecificationExecutor
    //  Page<SomeEntity> findAll(Specification<SomeEntity> specification, Pageable pageable);
    }
    

    通过正确设计的规范,pageable 的使用很容易:

    repo.findAll(SomeEntityRepository.findByCountryIdSpecification(countryId), pageable);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-19
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多