2015-08-17 58 views
6

我試圖在一個查詢中返回一組評分的平均值和計數。 在我發現瀏覽的例子之後,我在兩個查詢中很容易地管理它。例如: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); 

一個查詢現在返回收視率的平均等級和數量

回答

9

自己解決:

自定義類接收結果

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); 
+0

請確定您的自定義類 – Garry

+0

公共類AggregateResults {私人最終雙評級; 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; } } – formica

+0

謝謝...請將此添加到您的答案中,並與您的答案相關聯 – Garry

1

感謝。

你應該避免的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; 
}} 
+0

是的,我猜AVG()可能會返回null,儘管我認爲COUNT()會是0,如果沒有行匹配。 – formica

相關問題