Spring Data JPA - Custom Query with multiple aggregate functions in result(Spring Data JPA - 结果中具有多个聚合函数的自定义查询)
问题描述
我试图在一个查询中返回一组评分的平均值和计数.在我发现浏览的示例之后,我在两个查询中相当容易地管理它.例如:
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) 我需要一个新的类来获得结果:
1) I needed a new class for the results:
我必须在查询中引用该类:
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
推荐答案
自己解决了.
自定义类接收结果:
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);
这篇关于Spring Data JPA - 结果中具有多个聚合函数的自定义查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring Data JPA - 结果中具有多个聚合函数的自定义查询
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
