sql - JPA 存储库中使用 @Query 的多个 SELECT 语句
问题描述
我试图在存储库中使用带有“ nativeQuery = true ”的@Query注释来执行带有子网的select 语句。但它给了我以下错误:
org.postgresql.util.PSQLException:错误:“SELECT”处或附近的语法错误
以下是给我错误的查询
@Query(value="SELECT COUNT(cc.customer) AS tot FROM SELECT DISTINCT new RatingsAndReviews(c.customer,c.customerRating) FROM RatingsAndReviews AS c WHERE c.vehicle=?1 AS cc WHERE cc.customerRating=?2",nativeQuery = true)
Integer getNoOfRatingsForStars(Vehicle vehicle,double starNumber);
该查询基本上是从客户对特定车辆的 5 星中选择特定 starNumber 的评级计数。
单独的子 SELECT 查询在执行时给出了预期的结果,如下所示
@Query("SELECT DISTINCT new RatingsAndReviews(c.customer,c.customerRating) FROM RatingsAndReviews AS c WHERE c.vehicle=?1")
List<RatingsAndReviews> getCustomersWhoRatedVehicle(Vehicle vehicle);
我对上述查询的结果集是;RatingsAndReviews 对象数组
[
{
"customerRating": 2.0,
"customer": {
"customerId": 1,
},
},
},
{
"customerRating": 3.0,
"customer": {
"customerId": 2,
},
},
},
{
"customerRating": 2.0,
"customer": {
"customerId": 3,
},
},
}
]
所以我想要得到的是客户对特定号码的评分计数。的星星。例如,有多少 3 星评级、2 星评级……等等。
不设置'nativeQuery = true'的查询将是:
@Query("SELECT COUNT(cc.customer) AS tot FROM (SELECT DISTINCT new RatingsAndReviews(c.customer,c.customerRating) FROM RatingsAndReviews AS c WHERE c.vehicle=?1) AS cc WHERE cc.customerRating=?2")
Integer getNoOfRatingsForStars(Vehicle vehicle,double star);
这将给出以下错误
java.lang.IllegalArgumentException:查询方法公共抽象 java.lang.Integer 的验证失败
如果我对查询所做的事情是错误的,请纠正我,并且感谢任何排序帮助。
解决方案
首先在您的数据库查询客户端中手动测试查询的语法:例如
SELECT COUNT(cc.customer) AS tot
FROM
SELECT DISTINCT new RatingsAndReviews(c.customer,c.customerRating)
FROM RatingsAndReviews AS c
WHERE c.vehicle='some test value here' AS cc
WHERE cc.customerRating=<some test value here>
上面有很多语法问题,例如你不能使用new Type()
并且应该引用表名而不是类名。
推荐阅读
- css - 为什么 Chrome 总是添加 1px 的边框半径,即使特定的角设置为 0px?
- python - PyTorch:索引二维张量和行索引的二维张量
- watson-knowledge-catalog - 您是否有关于从不同数据目录转换到 IBM 数据目录的过程的信息?
- javascript - 如何将动态模态表单字段发送到 django
- javascript - 如何将这些“if”语句转换为算法
- bash - 如何在没有用户干预的情况下首次运行 crontab
- javascript - 找不到模块'regenerator-runtime/runtime'
- php - 防止在 PHP 中将重复项目添加到购物车
- dataframe - describe() 返回“错误:UndefVarError:描述未定义”
- recaptcha - Google reCAPTCHA 管理控制台的 URL 是什么?