Grails/Hibernate:如何通过 isnull(property) 排序以最后获得 NULL? [英] Grails/Hibernate: how to order by isnull(property) to get NULLs last?
问题描述
通常在按字段升序排序时,您首先获得 NULL 值,然后是更有趣的值.通常,您希望最后使用 NULL 值.在 MySQL 中,你可以这样做:
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;
但是,我使用带有 Hibernate 标准的 Grails,我完全不知道如何在那里执行此操作.这甚至以任何方式支持吗?有什么方法可以按自定义 SQL 表达式排序吗?我不想将我的所有标准重写为普通 SQL,只是为了让它正确排序.
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.
推荐答案
在休眠状态下,您可以尝试使用以下代码:
In hibernate you can try with this below code :
标准 c = ...;
Criteria c = ...;
c.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));
c.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));
这篇关于Grails/Hibernate:如何通过 isnull(property) 排序以最后获得 NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!