Grails/Hibernate:如何按 isnull(property) 排序以最后获取 NULL?
通常,当按字段升序排序时,您首先得到 NULL 值,然后是更有趣的值。通常,您希望最后使用 NULL 值。在 MySQL 中,您可以通过以下方式执行此操作:
SELECT * FROM people ORDER BY ISNULL(name), name;
但是,我使用的是具有 Hibernate 标准的 Grails,而且我完全不知道如何执行此操作那里。这是否以任何方式得到支持?有没有办法通过自定义 SQL 表达式进行排序?我不想将所有标准重写为纯 SQL,只是为了让它正确排序。
Normally when ordering ascending by a field, you get the NULL values first, and then the more interesting values. Often, you want NULL values last. In MySQL, you can do this with:
SELECT * FROM people ORDER BY ISNULL(name), name;
However, I'm using Grails with Hibernate criteria, and I have absolutely no idea how to do this there. Is this even supported in any way? Is there some way to order by a custom SQL expression? I'd hate to rewrite all my criteria to plain SQL just to get it to sort correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想订购并 HibernateCriteriaBuilder 在 GORM 中设置 NullPrecedence,则 AbstractHibernateCriteriaBuilder 提供您使用方法
.Order)" rel="noreferrer">order() ,您可以像常规 Hibernate示例
if you want to order and HibernateCriteriaBuilder to set NullPrecedence in GORM the AbstractHibernateCriteriaBuilder provies you with the method order() that you can set a org.hibernate.criterion.Order like regular Hibernate
Example
在休眠中,您可以尝试使用以下代码:
Criteria c = ...;
c.addOrder(Order.asc("名称").nulls(NullPrecedence.LAST));
In hibernate you can try with this below code :
Criteria c = ...;
c.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));
恐怕 Hibernate 中还没有:有一个 开放错误为了这。
不过,人们可以使用该错误注释中的
NativeSQLOrder
并尝试将适当的函数注入到HibernateCriteriaBuilder
中。您只需向HibernateCriteriaBuilder
类添加一个sqlOrder
方法,其作用与HibernateCriteriaBuilder.order()
大致相同。I'm afraid it's not even in Hibernate yet: there's an open bug for this.
Though, one could use
NativeSQLOrder
from that bug comments and try to inject a proper function intoHibernateCriteriaBuilder
. You only need to add asqlOrder
method toHibernateCriteriaBuilder
class, doing approximately same asHibernateCriteriaBuilder.order()
.