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

3

6

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.

Argive answered 26/4, 2011 at 8:35 Comment(1)
Looks like the Hibernate 'bug' has been fixed, hibernate.atlassian.net/browse/HHH-465. I would love to see updated answers for this.Stromboli
N
2

In hibernate you can try with this below code :

Criteria c = ...;

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

Naos answered 6/5, 2015 at 17:42 Comment(1)
same can be done for grails criteria too.. def userCriteria = User.createCriteria() userCriteria.addOrder(Order.asc(FIRST_NAME).nulls(NullPrecedence.LAST));Womack
C
5

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

     People.createCriteria().list (){
          order(org.hibernate.criterion.Order.asc('name')
                . nulls(org.hibernate.NullPrecedence.LAST)
           )
     }
Colby answered 8/1, 2016 at 20:59 Comment(0)
E
2

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 into HibernateCriteriaBuilder. You only need to add a sqlOrder method to HibernateCriteriaBuilder class, doing approximately same as HibernateCriteriaBuilder.order().

Eric answered 26/4, 2011 at 12:17 Comment(0)
N
2

In hibernate you can try with this below code :

Criteria c = ...;

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

Naos answered 6/5, 2015 at 17:42 Comment(1)
same can be done for grails criteria too.. def userCriteria = User.createCriteria() userCriteria.addOrder(Order.asc(FIRST_NAME).nulls(NullPrecedence.LAST));Womack

© 2022 - 2024 — McMap. All rights reserved.