java - Spring Data JPA - 结果中具有多个聚合函数的自定义查询

标签 java spring jpa spring-data aggregate-functions

我试图在一个查询中返回一组评分的平均值和计数。 在我发现浏览的示例之后,我在两个查询中相当容易地管理它。例如:

@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);

关于java - Spring Data JPA - 结果中具有多个聚合函数的自定义查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32049001/

相关文章:

java - JAXB:具有文本内容和属性的元素,使用 XJC 生成类

java - 非实用静态方法

Spring 启动@Transactional

java - 对多个字段施加唯一约束

java - phpMyAdmin 数据库的连接字符串

java - 如何将源列表的每组两个元素转换为转换后的列表?

java - 如何检查 ImageView 中是否有图像并跳过该图像到下一个 ImageView

java - Spring改变事务隔离模式

java - Hibernate boolean 字段映射问题

java - 无法使用 @ManagedProperty 显示来自数据库的结果