首页 > 解决方案 > 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 的验证失败

如果我对查询所做的事情是错误的,请纠正我,并且感谢任何排序帮助。

标签: sqlpostgresqlspring-bootspring-data-jpa

解决方案


首先在您的数据库查询客户端中手动测试查询的语法:例如

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()并且应该引用表名而不是类名。


推荐阅读