【发布时间】:2021-02-24 04:49:44
【问题描述】:
我得到了这个存储库代码:
@Query(value = "select distinct r from Reference r " +
"inner join fetch r.persons " +
"left outer join fetch r.categories " +
"left outer join fetch r.keywords " +
"left outer join fetch r.parentReferences",
countQuery = "select count(distinct r.id) from Reference r " +
"inner join r.persons " +
"left outer join r.categories " +
"left outer join r.keywords " +
"left outer join r.parentReferences")
Page<Reference> findsAllRelevantEntries(Pageable pageable);
当我对该查询运行测试时,我收到了 Hibernate 警告:HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!
@Test
void testFindAllRelevantAsync() throws ExecutionException, InterruptedException {
CompletableFuture<Page<Reference>> all = referenceService.findAllRelevantAsync(PageRequest.of(1, 20));
CompletableFuture.allOf(all).join();
assertThat(all.get()).isNotNull();
assertThat(all.get()).isNotEmpty();
}
存储库代码封装在此处未显示的服务方法中。它(服务方法)只是将来自服务的调用编组到存储库并返回。
此外,生成的 sql 查询不会生成 limit 子句。虽然它确实触发了两个查询。
一个用于count,另一个用于获取所有记录。
因此它会获取所有记录并在内存中应用分页。
这会导致查询执行速度非常慢。
我怎样才能使分页与这个查询一起工作?
编辑
我知道这里经常被建议作为解决方案: How can I avoid the Warning "firstResult/maxResults specified with collection fetch; applying in memory!" when using Hibernate?
有没有办法使用 Spring Data JPA 实现分页?
我不想硬连线EntityManager,我也不想
从BasicTransformerAdapter扩展代码
【问题讨论】:
-
谢谢,但请看我的编辑
标签: spring-boot hibernate jpa spring-data-jpa