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

前端 未结 2 1113
我在风中等你
我在风中等你 2020-12-29 09:00

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:<

相关标签:
2条回答
  • 2020-12-29 09:28

    Thanks.

    You should prevent NPEs and hibernate parsing tuple errors as following :

    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;
    }}
    
    0 讨论(0)
  • 2020-12-29 09:53

    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);
    
    0 讨论(0)
提交回复
热议问题