【问题标题】:Spring-Data-JPA Specification with Aggregate function具有聚合功能的 Spring-Data-JPA 规范
【发布时间】:2019-05-06 22:16:54
【问题描述】:

我们如何使用规范编写下面的查询

SELECT e.id, e.name, count(e.id) 
FROM Employee e INNER JOIN Department d
WHERE e.id = d.empId;

当我们使用规范时,即使在多选中提到它也不会选择count()。

任何想法,当我们使用 JPA findAll 方法时,如何在规范中包含计数列。

尝试了多选,但是当它传递给规范时,它只查询非聚合列。

Expression<Long> countExp = cb.count(root.get("id"));
 CriteriaQuery<Employee> select =
 criteriaQuery.multiselect(root.get("id"), root.get("name"), countExp);

但它会生成如下查询:

SELECT e.id, e.name
FROM Employee e INNER JOIN Department d
WHERE e.id = d.empId;

似乎有同样的问题: JpaSpecificationExecutor : complex queries with specifications

Why the multiselect method in JPA does not work

【问题讨论】:

    标签: jpa spring-data-jpa specifications


    【解决方案1】:

    为了解决上述问题,创建了自己的 JPARepository 实现并从 SimpleJpaRepository 覆盖 getQuery 方法

    private TypedQuery<Employee> getQuery(Specification<Employee> spec, Sort sort) {
            CriteriaBuilder builder = this.em.getCriteriaBuilder();
            CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
            Root<Employee> root = this.applySpecificationToCriteria(spec, query);
    
            query.multiselect(root.get("id"), root.get("name"),
                    builder.count(root.get("id")).alias("count"));
    
            if (sort != null) {
                query.orderBy(QueryUtils.toOrders(sort, root, builder));
            }
    
            return this.em.createQuery(query);
        }
    

    【讨论】:

    • 我用的是spring boot 1.5.22,至少在这个版本中applySpecificationToCriteria方法是私有的,所以我不能用。
    猜你喜欢
    • 2016-07-22
    • 2020-05-20
    • 2016-02-17
    • 2017-01-12
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多