【问题标题】:Hibernate generate sql query missing "(" characterHibernate生成sql查询缺少“(”字符
【发布时间】:2021-10-18 01:31:48
【问题描述】:

我在使用@Query 时遇到了一个问题

    @Query(value = "select c.id as id, c.store_id as store_id, c.name as name, c.type as type, c.rate as rate, " +
        "(select count(pc.partner_id) from partner_commission pc where pc.commission_id = c.id) as number_of_partner " +
        "from commission c join partner_commission pc on c.id = pc.commission_id where c.store_id=:storeId", nativeQuery = true)
    Page<Commission> findCommissionForManagement(@Param("storeId") Long storeId, Pageable pageable);

我已经在数据库 (postgresql) 上测试了这个脚本,它成功了!但是,hibernate生成的sql脚本如下:

Hibernate: select c.id as id, c.store_id as store_id, c.name as name, c.type as type, c.rate as rate, (select count(pc.partner_id) from partner_commission pc where pc.commission_id = c.id) as number_of_partner from commission c join partner_commission pc on c.id = pc.commission_id where c.store_id=? limit ?
Hibernate: select count(pc) from partner_commission pc where pc.commission_id = c.id) as number_of_partner from commission c join partner_commission pc on c.id = pc.commission_id where c.store_id=?
2021-08-16 04:05:44.645  WARN 15976 --- [llCommissions-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42601
2021-08-16 04:05:44.645 ERROR 15976 --- [llCommissions-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: syntax error at or near ")"
  Position: 74

希望能得到帮助

【问题讨论】:

    标签: spring postgresql hibernate spring-data-jpa


    【解决方案1】:

    似乎@Query 错误地分解了子查询。可以使用 Join 重构查询吗?

    这是我的建议,未经测试,但我希望您可以进一步调试它以获得您想要的结果。

    SELECT
        c.id AS id,
        c.store_id AS store_id,
        c.name AS name,
        c.type AS type,
        c.rate AS rate
        pc.count AS number_of_partner
    FROM
        commission c
    LEFT JOIN (
        SELECT
            id,
            COUNT(*) AS count
        FROM
            partner_commission
        GROUP BY
            partner_commission.id
    ) AS pc
    ON pc.id = c.store_id
    WHERE
        c.store_id = :storeId
    

    【讨论】:

    • 完全没问题。
    【解决方案2】:

    看起来像一个 Spring Data JPA 错误。您可以尝试通过在 @Query 注释中提供自定义计数查询来解决此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多