Hibernate Criteria order by a specific state

烂漫一生 提交于 2019-12-03 17:05:33

You can order by a conditional value...

(NHibernate way, anyone know the equivalent in Hibernate?)

.AddOrder(Order.Asc(
    Projections.Conditional(
         Restrictions.EqProperty("addr.state", "user.state"), Projections.Constant(0), Projections.Constant(1))))
.AddOrder(Order.Asc("addr.state"))

translates to...

order by 
    case when addr.state = user.state then 0 else 1 end,
    addr.state

I'm sure the there is a really cleaver way todo this but my initial thought is just to do two queries. First with the state == 'Maryland' and second state != 'Maryland'. And stitch the results together your self.

It is possible using HQL:

from Person p order by case when p.addr.state = 'Maryland' then '0' else '1' end asc, p.addr.state asc

I've prepared an example over on github

https://github.com/gid79/q4510810-hibernate-criteria-order-by-a-specific-state

Harish, If I understand it right, all you will have to do is add order to the criteria. List addresses = sess.createCriteria(PRSN_ADDRESS.class) .addOrder( Order.asc(user.state) ) .list();

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