【问题标题】:Spring Data JPA: findAll with Specification and Pageable fails on count querySpring Data JPA:findAll with Specification and Pageable 在计数查询中失败
【发布时间】:2018-07-09 23:05:25
【问题描述】:

我正在尝试在 JpaSpecificationExecutor 的 findAll(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...),它们与报告具有一对一的关系。

下面是他的一个关系的 getter 示例:

@OneToOne(fetch = FetchType.LAZY, mappedBy = "report")
@Fetch(FetchMode.JOIN)
public Entity1 getEntity1() {
    return this.entity1;
}

现在,当我使用我的规格致电 List&lt;T&gt; findAll(Specification&lt;T&gt; spec) 时,一切正常。但是当我调用 Page&lt;T&gt; findAll(Specification&lt;T&gt; spec, Pageable pageable) 时,到达计数查询失败时会出现下一个异常:

“例外”: "org.springframework.dao.InvalidDataAccessApiUsageException", “消息”:“org.hibernate.QueryException:查询指定连接 正在获取,但获取的关联的所有者不存在 选择列表... [select count(generatedAlias0) from com.xxx.yyy.editor.entity.Report as generatedAlias0 inner join fetch generatedAlias0.report1 as generatedAlias1 内连接获取 generatedAlias0.report2 as generatedAlias2..."

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

我使用的是 Spring Boot 1.5.9。

提前谢谢你。

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

【问题讨论】:

    标签: java count spring-data-jpa fetch specifications


    【解决方案1】:

    我遇到了和你一样的问题。这里的问题是分页的时候会调用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);
        }; 
    

    }

    您可以参考以下文章:

    希望有帮助

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 2018-07-25
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      相关资源
      最近更新 更多