我正在尝试获取 findAll(Specification<T> spec, Pageable pageable)
上的一些数据JpaSpecificationExecutor 的。
我的规范是:
public static Specification<Report> isTemplate(boolean isTemplate) {
return (root, query, cb) ->{
root.fetch("entity1");
root.fetch("entity2");
root.fetch("entity3");
root.fetch("entity4");
root.fetch("entity5");
return cb.equal(root.get("isTemplate"), isTemplate);
};
}
其中报告有 5 个与报告一一对应的子表(entity1...)。
这是他的一个关系的 getter 的示例:
@OneToOne(fetch = FetchType.LAZY, mappedBy = "report")
@Fetch(FetchMode.JOIN)
public Entity1 getEntity1() {
return this.entity1;
}
现在,当我调用List<T> findAll(Specification<T> spec)
时根据我的规范,一切正常。但是当我调用 Page<T> findAll(Specification<T> spec, Pageable pageable)
当到达计数查询时失败,给出下一个异常:
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException", "message": "org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list... [select count(generatedAlias0) from com.xxx.yyy.editor.entity.Report as generatedAlias0 inner join fetch generatedAlias0.report1 as generatedAlias1 inner join fetch generatedAlias0.report2 as generatedAlias2..."
任何其他人都面临此问题或知道为什么会发生这种情况。
我使用的是 Spring Boot 1.5.9。
提前谢谢您。
PD。我正在使用 fetch 来获取一个查询中的所有关系。
最佳答案
我也遇到了和你一样的问题。这里的问题是分页时,会调用count查询,但是count查询不允许fetch。
为了解决这个问题,我们必须通过检查查询的结果类型来防止计数时获取,并且仅在结果类型不长时才获取(当结果类型为长时,意味着执行了计数查询),如下所示:
public static Specification<Report> isTemplate(boolean isTemplate) {
return (root, query, cb) -> {
if (query.getResultType() != Long.class && query.getResultType() != long.class) {
root.fetch("entity1");
root.fetch("entity2");
root.fetch("entity3");
root.fetch("entity4");
root.fetch("entity5");
}
return cb.equal(root.get("isTemplate"), isTemplate);
};
}
您可以引用以下文章:
- https://codingexplained.com/coding/java/spring-framework/fetch-query-not-working-spring-data-jpa-pageable
- https://coderanch.com/t/656073/frameworks/Spring-Data-fetch-join-Specification
希望有帮助
关于java - Spring 数据JPA : findAll with Specification and Pageable fails on count query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51255134/