【问题标题】:QuerySyntaxException: expecting CLOSE, found '.'QuerySyntaxException:期待关闭,找到“。”
【发布时间】:2019-11-30 15:04:16
【问题描述】:

我想将此 SQL 查询重写为 JPQL 并使用 JPA 投影:

SELECT count(id) as count, status, error_class, error_message, id, settlement_status_raw 
FROM `payment_transactions` 
WHERE `payment_transactions`.`terminal_id` = 16 
AND (created_at > '2019-06-01 00:00:00.000000') 
AND (`payment_transactions`.`status` != 'approved') 
GROUP BY `payment_transactions`.`error_message`  ORDER BY count DESC

我试过了:

@Query(value = "SELECT new org.plugin.service.PaymentTransactionsDeclineReasonsDTO(e.id, count(id) as e.count, e.status, e.error_class, e.error_message) " +
            " FROM payment_transactions e " +
            " WHERE e.terminal_id = :id AND (e.created_at > :created_at) " +
            " AND (e.status != 'approved') " +
            " GROUP BY e.error_message " +
            " ORDER BY e.count DESC")

但我得到错误:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE, found '.' near line 1, column 96 [SELECT new org.plugin.service.PaymentTransactionsDeclineReasonsDTO(e.id, count(id) as e.count, e.status, e.error_class, e.error_message)  FROM payment_transactions e  WHERE e.terminal_id = :id AND (e.created_at > :created_at)  AND (e.status != 'approved')  GROUP BY e.error_message  ORDER BY e.count DESC]"}}

你能给我一些建议吗?如何正确地用 JPQL 重写这个查询?

【问题讨论】:

  • 您的查询是原生查询,必须使用nativeQuery = "true"

标签: java jpa spring-data-jpa jpa-2.0 jpa-2.1


【解决方案1】:

看起来问题出在e.count 处。

看来,应该是count(e.id) as count。也许count(1) as count 会返回相同的结果。

【讨论】:

  • 感谢@Jens 的澄清。 count(1) 也仅适用于本机查询。
【解决方案2】:

我同意 Mike.F e.count 不是一个有效的表达方式。 但是语句有更多的问题:

  • e.ide.statuse.error_class 不是GROUP BY 的一部分,因此它们不能在选择中使用。将它们添加到 GROUP BY 或使用聚合函数,例如 MAXMIN

  • 您不能在构造函数表达式中定义别名。

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 2016-10-21
    • 2019-12-01
    • 2021-06-16
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2012-12-31
    • 2013-12-25
    相关资源
    最近更新 更多