首页 文章

Spring Data JPA:带有规范和Pageable的findAll在计数查询时失败

提问于
浏览
0

我正在尝试在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个子表(entity1 ...),它们与报告一对一关系 .

这是他的一个关系的吸气剂的例子:

@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:查询指定的连接提取,但提取的关联的所有者在选择列表中不存在... [select count(generatedAlias0)从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来获取一个查询中的所有关系 .

1 回答

  • 0

    我遇到了和你一样的问题 . 这里的问题是分页时,它会调用一个count查询,但count查询不允许fetch .

    为了解决这个问题,我们必须通过检查查询的结果类型来防止在计数时获取,并且只有在结果类型不长时才获取(当结果类型为long时,表示执行了计数查询),如下所示:

    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);
        };
    

    }

    您可以参考以下文章:

    希望有所帮助

相关问题