【问题标题】:Spring Data JPA - Custom Query with multiple aggregate functions in resultSpring Data JPA - 结果中具有多个聚合函数的自定义查询
【发布时间】:2015-11-10 00:11:53
【问题描述】:

我试图在一个查询中返回一组评分的平均值和计数。 在我发现浏览的示例之后,我在两个查询中相当容易地管理它。例如:

@Query("SELECT AVG(rating) from UserVideoRating where videoId=:videoId")
public double findAverageByVideoId(@Param("videoId") long videoId);

但只要我想在同一个查询中计算平均值和计数,问题就开始了。经过几个小时的实验,我发现这很有效,所以我在这里分享它。希望对你有帮助。

1) 我需要一个新的类来获得结果:

我必须在查询中引用该类:

@Query("SELECT new org.magnum.mobilecloud.video.model.AggregateResults(AVG(rating) as rating, COUNT(rating) as TotalRatings) from UserVideoRating where videoId=:videoId")
public AggregateResults findAvgRatingByVideoId(@Param("videoId") long videoId);

一个查询现在返回平均评分和评分计数

【问题讨论】:

  • 这是否也会填充其他属性。

标签: java spring jpa spring-data aggregate-functions


【解决方案1】:

自己解决了。

自定义类接收结果:

public class AggregateResults {

    private final double rating;
    private final int totalRatings;

    public AggregateResults(double rating, long totalRatings) {
        this.rating = rating;
        this.totalRatings = (int) totalRatings;
    }

    public double getRating() {
        return rating;
    }

    public int getTotalRatings() {
        return totalRatings;
    }
}

@Query("SELECT new org.magnum.mobilecloud.video.model.AggregateResults(
    AVG(rating) as rating, 
    COUNT(rating) as TotalRatings) 
    FROM UserVideoRating
    WHERE videoId=:videoId")
public AggregateResults findAvgRatingByVideoId(@Param("videoId") long videoId);

【讨论】:

  • 请定义您的自定义类
  • public class AggregateResults { private final double rating;私人最终int totalRatings; public AggregateResults(double rating, long totalRatings) { this.rating = rating; this.totalRatings = (int) totalRatings; } public double getRating() { 返回评级; } public int getTotalRatings() { return totalRatings; } }
  • 谢谢...请将此添加到您的答案中并相关
  • 您的自定义类是否标记为“实体”?我有错误“实体没有定义主键属性”
  • @jmhostalet 您需要(at)Entity 针对映射到表的类,是的,但不是自定义结果类。您的错误听起来像是映射到 db 表的类的问题。您需要在该类的某处有一个用 (at)Id 标记的列。例如: (at)Id (at)GeneratedValue(strategy = GenerationType.AUTO) private long id;抱歉,对话不允许我输入“at”符号
【解决方案2】:

谢谢。

您应该防止 NPE 和休眠解析元组错误如下:

public class AggregateResults {

private final double rating;
private final int totalRatings;

public AggregateResults(Double rating, Long totalRatings) {
    this.rating = rating == null ? 0 : rating;
    this.totalRatings = totalRatings == null ? 0 : totalRatings.intValue();
}

public double getRating() {
    return rating;
}
public int getTotalRatings() {
    return totalRatings;
}}

【讨论】:

  • 是的,我猜 AVG() 可能会返回 null,尽管我认为 COUNT() 会是 0,如果没有匹配的行。
猜你喜欢
  • 2019-02-20
  • 1970-01-01
  • 2015-12-07
  • 2015-03-25
  • 2013-11-19
  • 2020-06-17
  • 2017-10-15
  • 2013-02-05
  • 2017-12-13
相关资源
最近更新 更多