[英]Spring Data JPA - Custom Query with multiple aggregate functions in result
我試圖在一個查詢中返回一組平均值和一組評級。 在我發現瀏覽的示例之后,我在兩個查詢中相當容易地管理它。 例如:
@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);
一個查詢現在返回平均評級和評級計數
解決了自己。
自定義類來接收結果:
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);
謝謝。
你應該防止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.