简体   繁体   English

Spring Data JPA - 结果中包含多个聚合函数的自定义查询

[英]Spring Data JPA - Custom Query with multiple aggregate functions in result

I was trying to return an average and count of a set of ratings in one query. 我试图在一个查询中返回一组平均值和一组评级。 I managed it fairly easily in two queries following the example I found browsing. 在我发现浏览的示例之后,我在两个查询中相当容易地管理它。 For example: 例如:

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

but as soon as I wanted an average and a count in the same query, the trouble started. 但是只要我想在同一个查询中获得平均值和一个计数,麻烦就开始了。 After many hours experimenting, I found this worked, so I am sharing it here. 经过几个小时的实验,我发现这很有效,所以我在这里分享。 I hope it helps. 我希望它有所帮助。

1) I needed a new class for the results: 1)我需要一个新的结果类:

The I had to reference that class in the query: 我必须在查询中引用该类:

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

One query now returns average rating and count of ratings 一个查询现在返回平均评级和评级计数

Solved myself. 解决了自己。

Custom class to receive results: 自定义类来接收结果:

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

and

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

Thanks. 谢谢。

You should prevent NPEs and hibernate parsing tuple errors as following : 你应该防止NPE和hibernate解析元组错误,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM