Spring Data JPA:查找所有具有规范和可分页的计数查询失败



我正在尝试获取有关JpaSpecificationExecutorfindAll(Specification<T> spec, Pageable pageable)的一些数据。

我的规格是:

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 个子表(实体 1...),与报告具有 1 对 1 的关系。

以下是他的一个关系的获取者的例子:

@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)时,到达计数查询时失败,给出下一个异常:

"例外": "org.springframework.dao.InvalidDataAccessApiUsageException", "message": "org.hibernate.QueryException: query 指定的连接 正在获取,但已提取关联的所有者不在 选择列表...[从中选择计数(生成的别名0) com.xxx.yyy.editor.entity.report as generated Alias0 inner join fetch 生成别名0.report1 作为生成的别名 1 内部联接提取 生成别名0.报告2 作为生成的别名2...">

任何其他人都面临这个问题或知道为什么会发生这种情况。

我正在使用 Spring Boot 1.5.9。

提前谢谢你。

PD.我正在使用 fetch 在一个查询中获取所有关系。

我遇到了和你一样的问题。这里的问题是在分页时,它会调用计数查询,但计数查询不允许提取。

为了克服这个问题,我们必须通过检查查询的结果类型来防止计数时的 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

希望有帮助

最新更新