Spring Data JPA - 自定义查询,结果中有多个聚合函数

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

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

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


答案 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);

答案 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;
}}

推荐