如何在 JPQL 中编写 Order by 表达式

发布于 2024-10-06 10:52:51 字数 791 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

被你宠の有点坏 2024-10-13 10:52:51

对于命名查询,(ORDER BY ( a.id = :id ) 或 ORDER BY (:id )) 将不起作用,因为 DSC/ASC 无法在运行时参数化。

1) 如果排序元素在运行时发生变化,则采用动态方式。

String query = "SELECT a FROM Article a ORDER BY "+orderElement+" DESC, a.id DESC";
entityManager.createQuery(query).getResultList();

2) 如果排序元素是固定的,则实体 bean 中的静态方式。

字段级别:

@OrderBy("id ASC")
List<Article> articles;

方法级别:

@OrderBy("id DESC")
public List<Article> getArticles() {...};

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.

String query = "SELECT a FROM Article a ORDER BY "+orderElement+" DESC, a.id DESC";
entityManager.createQuery(query).getResultList();

2) Static way in entity bean if ordering element is fixed.

Field level:

@OrderBy("id ASC")
List<Article> articles;

Method level:

@OrderBy("id DESC")
public List<Article> getArticles() {...};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文