sql - 使用 @Formula(休眠注释)时无法提取 ResultSet
问题描述
在我的应用程序中有courses
和course_ratings
表(我使用 MySQL)。在course_ratings
表中是表的外键courses
和名为rating
INT 的列。
我将在一个示例中展示我的问题:当我从 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);
解决方案
这是我的解决方案!
@Formula("SELECT AVG(cr.rating) FROM course_ratings cr WHERE cr.course_id = course_id")
我已更改courseId
为,course_id
因为它是原始 SQL,而不是 JPQL
推荐阅读
- docker - Digital Ocean docker 容器注册表可以与 Jenkins 一起使用吗?
- java - 在java中调用没有正文的Post请求
- hangfire - Hangfire 重试后发送电子邮件
- php - 数据库中的 sql 在 php 中给出不同的结果
- python - Discord.py - 更改默认帮助命令
- ios - 如何覆盖 NumberFormatter 字符串和数字方法
- css - 如何使 CSS Grid 中的图像彼此相邻并在空间不足时跳转到另一行
- c# - 有没有办法从字符串调用函数?
- python - Streamlit 中的动态 div 创建
- java - 如何使用 AuthenticationProvider 显示登录错误