首页 > 解决方案 > 使用 @Formula(休眠注释)时无法提取 ResultSet

问题描述

在我的应用程序中有coursescourse_ratings表(我使用 MySQL)。在course_ratings表中是表的外键courses和名为ratingINT 的列。

我将在一个示例中展示我的问题:当我从 db 下载 id 为 1 的课程时,我想获取表course_ratings的外键为 1 的所有行,然后计算所有这些行的列courses的平均值。rating

为此,我决定使用@Formula注释

看看我的实体:

    @Entity
    @Table(name = "courses")
    public class Course {
        @Id
        @GeneratedValue(generator = "inc")
        @GenericGenerator(name = "inc", strategy = "increment")
        private int courseId;
        @NotBlank(message = "Add the course's title!")
        private String title;
        private String description;

        @Formula("SELECT AVG(cr.rating) FROM course_ratings cr WHERE cr.course_id = courseId")
        private double averageRating;
    
        @OneToMany(mappedBy = "course")
        private Set<CourseRating> ratings; 
}

里面的这个 SQL@Formula是正确的,但是在findById(Integer id)从 JpaRepository 调用方法之后,我得到了这个错误:

2021-07-14 20:26:26.314  WARN 15268 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1064, SQLState: 42000
2021-07-14 20:26:26.314 ERROR 15268 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : (conn=248) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT AVG(cr.rating) FROM course_ratings cr WHERE cr.course_id = 1 as formul...' at line 1
2021-07-14 20:26:26.323  INFO 15268 --- [nio-8080-exec-3] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command

org.hibernate.exception.SQLGrammarException: could not extract ResultSet

编辑:如果它很重要,我不知道,但我已将 average_rating 列添加为DECIMAL

ALTER TABLE courses ADD COLUMN average_rating DECIMAL(3, 2);

标签: sqlhibernatejpaformula

解决方案


这是我的解决方案!

@Formula("SELECT AVG(cr.rating) FROM course_ratings cr WHERE cr.course_id = course_id")

我已更改courseId为,course_id因为它是原始 SQL,而不是 JPQL


推荐阅读