我试图在一个查询中返回一组平均值和一组评分。 在我发现浏览的示例之后,我在两个查询中相当容易地管理它。例如:
@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);
现在,一个查询会返回平均评分和评分计数
答案 0 :(得分:14)
解决了自己。
接收结果的自定义类:
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);
答案 1 :(得分:2)
感谢。
你应该防止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;
}}