Search code examples
hibernategrailsnullcriteria

Grails/Hibernate: how to order by isnull(property) to get NULLs last?


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.


Solution

  • In hibernate you can try with this below code :

    Criteria c = ...;

    c.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));