gpt4 book ai didi

java - 按 JPA 标准查询中的聚合字段过滤

转载 作者:行者123 更新时间:2023-12-02 00:32:25 26 4
gpt4 key购买 nike

我在编写按聚合排序的规范时遇到问题。假设我有 2 个实体:

@Entity
public class Property {

@Id
@GeneratedValue
private Long id;

@OneToMany
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private List<Feedback> ratings;
}

@Entity
public class Feedback {

@Id
@GeneratedValue
private Long id;

@Column(nullable = false)
private Integer rating;
}

我想要实现的是获取平均评级高于给定阈值的所有属性。以下是我使用万能的 Google 得出的结论:

private static Specification<Property> ratingsSpec(Double minRating) {
return (root, query, criteriaBuilder) -> {
ListJoin<Property, Feedback> feedbackJoin = root.join(Property_.ratings);
return criteriaBuilder.greaterThanOrEqualTo(criteriaBuilder.avg(feedbackJoin.get(Feedback_.rating)), minRating);
};
}

但是当尝试运行时,我收到以下错误:

Invalid use of aggregate function "AVG(CAST(FEEDBACK2_.RATING AS DOUBLE))"; 
SQL statement:
select property0_.id as id1_1_, property0_.additional_info as addition2_1_, property0_.address_line1 as address_3_1_, property0_.address_line2 as address_4_1_, property0_.city as city5_1_, property0_.postcode as postcode6_1_, property0_.area_sqm as area_sqm7_1_, property0_.rooms as rooms8_1_, property0_.type as type9_1_, property0_.version as version10_1_ from property property0_ inner join property_ratings ratings1_ on property0_.id=ratings1_.property_id inner join feedback feedback2_ on ratings1_.ratings_id=feedback2_.id where 1=1 and avg(cast(feedback2_.rating as double))>=3.9 [90054-199]

我准确地复制了错误,以免忽略任何重要的内容,显然那里的字段比我上面提到的要多。

现在,我发现查询存在问题,条件绝对应该位于 having 子句中,而不是 where 中,而且我缺少 组by 子句。但我怎样才能做到这一点呢?任何帮助将不胜感激。

奖励问题:如何按相同值排序? ;)

最佳答案

实际上已经成功地使用查询来做到这一点。我不确定这是否是最好的解决方案,所以如果有人有任何意见,我会洗耳恭听。这是工作解决方案:

private static Specification<Property> ratingsSpec(Double minRating) {
return (root, query, criteriaBuilder) -> {
ListJoin<Property, Feedback> feedbackJoin = root.join(Property_.ratings);
Expression<Double> avg = criteriaBuilder.avg(feedbackJoin.get(Feedback_.rating));
return query.groupBy(root).having(criteriaBuilder.greaterThanOrEqualTo(avg, minRating)).getRestriction();
};
}

关于java - 按 JPA 标准查询中的聚合字段过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58001903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com