【问题标题】:QuerySyntaxException: expecting OPEN, found 'DESC' near line 1QuerySyntaxException:期待 OPEN,在第 1 行附近发现“DESC”
【发布时间】:2019-12-01 10:16:06
【问题描述】:

我想使用 JPA 实现这个 JPQL 查询:

String hql = "SELECT new org.plugin.service.PaymentTransactionsDeclineReasonsDTO(count(e.id) as count, e.status, e.error_class, e.error_message) " +
                " FROM " + PaymentTransactions.class.getName() + " e " + 
                " WHERE e.terminal_id = :terminal_id AND (e.createdAt > :created_at) " + 
                " AND (e.status != 'approved') " +
                " GROUP BY e.error_message " +
                " ORDER BY count DESC";  

但我收到错误:Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting OPEN, found 'DESC' near line 1, column 334 [SELECT new org.plugin.service.PaymentTransactionsDeclineReasonsDTO(count(e.id) as count, e.status, e.error_class, e.error_message) FROM org.datalis.plugin.entity.PaymentTransactions e WHERE e.terminal_id = :terminal_id AND (e.createdAt > :created_at) AND (e.status != 'approved') GROUP BY e.error_message ORDER BY count DESC]

按数量排序的正确方法是什么?

【问题讨论】:

  • 不要为列指定别名count,因为它是 SQL 中的关键字。将其替换为不同的名称,可能是 amount 或其他名称。在 SELECT 块和 ORDER BY 子句中替换它。读取count 时,SQL 将期待一个左括号! count(e.id) as count 应该是 count(e.id) as amountORDER BY count DESC 应该是 ORDER BY amount DESC

标签: java jpa jpa-2.0 jpql jpa-2.1


【解决方案1】:

您不能将 SQL 关键字 COUNT 用作别名(即使是小写字母也不行)。没有办法,你必须使用不是 SQL 关键字的别名(如SELECTFROMAS 等)。

我认为您应该使用以下查询,这至少可以摆脱您发布的错误:

String hql = "SELECT "
    + "new org.plugin.service.PaymentTransactionsDeclineReasonsDTO("
    + "count(e.id) as amount, " // <--- alias name changed here
    + "e.status, "
    + "e.error_class, "
    + "e.error_message) "
    + "FROM "
    + PaymentTransactions.class.getName() + " e " 
    + "WHERE "
    + "e.terminal_id = :terminal_id "
    + "AND (e.createdAt > :created_at) "
    + "AND (e.status != 'approved') "
    + " GROUP BY e.error_message "
    + " ORDER BY amount DESC";  // <-- alias name used here

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2019-08-12
    • 2019-08-17
    • 2016-07-28
    • 1970-01-01
    • 2021-10-05
    • 2023-02-13
    • 2016-02-21
    • 2019-11-30
    相关资源
    最近更新 更多