如何在 JPQL 中编写 Order by 表达式
PostgreSQL 和 MySQL 提供将表达式写入 SQL 查询中的 ORDER BY 子句。它允许按某些列对项目进行排序,但特殊值位于顶部。 SQL 看起来像这样。 (在 Postgres 中工作)
select * from article order by id = 4, id desc;
现在我想在 JPQL 中编写它,但它不起作用。我的尝试是:
@NamedQuery(name = "Article.special", query = "SELECT a FROM Article a ORDER BY ( a.id = :id ) DESC, a.id DESC")
这是带有 Hibernate 驱动程序的 JPA 1.0。应用程序服务器在部署时抛出此异常。
ERROR [SessionFactoryImpl] Error in named query: Article.special
org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: = near line 1, column 73 [SELECT a FROM cz.cvut.fel.sk.model.department.Article a ORDER BY ( a.id = :id ) DESC, a.id DESC]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
多谢。
PostgreSQL and MySQL offers to write expression into ORDER BY
clause in SQL query. It allows to sort items by some column but the special values are on the top. The SQL looks like this one. ( works in Postgres )
select * from article order by id = 4, id desc;
Now I want to write it in the JPQL but it doesn't work. My attempt is:
@NamedQuery(name = "Article.special", query = "SELECT a FROM Article a ORDER BY ( a.id = :id ) DESC, a.id DESC")
This is JPA 1.0 with Hibernate driver. Application server throws this exception on deploy.
ERROR [SessionFactoryImpl] Error in named query: Article.special
org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: = near line 1, column 73 [SELECT a FROM cz.cvut.fel.sk.model.department.Article a ORDER BY ( a.id = :id ) DESC, a.id DESC]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于命名查询,(ORDER BY ( a.id = :id ) 或 ORDER BY (:id )) 将不起作用,因为 DSC/ASC 无法在运行时参数化。
1) 如果排序元素在运行时发生变化,则采用动态方式。
2) 如果排序元素是固定的,则实体 bean 中的静态方式。
字段级别:
方法级别:
For a named query, (ORDER BY ( a.id = :id ) or ORDER BY (:id )) won't work as DSC/ASC can't be parametrized at run-time.
1) Dynamic way if ordering element varies at runtime.
2) Static way in entity bean if ordering element is fixed.
Field level:
Method level: