使用可分页并仍然查询每个可能的项目

时间:2016-07-01 09:22:34

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

为了加快我们的应用程序,我们计划限制执行查询时获得的结果量。问题是简单的LIMIT不适用于JPQL,因此我们尝试使用Pageables创建变通方法。

结果是正确的结果量可视化,这是非常好的,但它比预期的要长,并且当监视执行的查询时,它似乎仍然在查询每个对象而不是请求的量。看起来像过滤后'它检索了完整的结果。

存储库:

public interface CompRepository extends JpaRepository<Comp, Integer> {
...

    @Query(value = "select distinct c from Comp c" +
            " left join fetch c.titles ti " +
            " left join fetch c.messages msg  " +
            " where c.status = 'PUBLISHED' " +
            " order by c.id desc",
        countQuery = "select count(c) from Comp c")
    Page<Compass> findByLatest(Pageable page);

...
}

服务:

public class CompService {
    @Autowired
    private CompRepository repository;
...

    public static List<Comp> findLatest() {
        int amount = 5; /*hardcoded*/

        Page<Compass> page = getRepository().findByLatest(new PageRequest(1, amount).first());

        return page.getContent();
    }

...
}

波姆:

...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>1.3.0.RELEASE</version>
</dependency>
....

如果您需要更多代码:喊叫!

有人知道问题可能是什么吗?

如果没有,有什么建议可以更好地找到JPQL中缺少LIMIT的方法吗?

___ SOLUTION ___

删除连接已修复它。更具体地说,问题在于提取&#39;所以如果我删除了&#39; fetch&#39;那么我可以选择保留连接。从查询来看,但我认为没有任何用处。

0 个答案:

没有答案