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

跟風遠走 提交于 2019-11-30 04:45:09

问题


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.


回答1:


In hibernate you can try with this below code :

Criteria c = ...;

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




回答2:


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)
           )
     }



回答3:


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().



来源:https://stackoverflow.com/questions/5787855/grails-hibernate-how-to-order-by-isnullproperty-to-get-nulls-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!