Hibernate Criteria order by a specific state

2019-03-31 08:30发布

Hi In the database, we have a PRSN_ADDRESS table which has many addresses. A user is shown these addresses in a grid. The requirement is show the addresses associated with this user's state first and then show all other states.

For example, say the table has 10 records with 5 of the addresses having state as Maryland, 2 from PA and 3 from NJ. Now if the user is associated with Maryland, we need to show all the 10 addresses, but Maryland addresses should show up in the first five and then the other 5 in any order.

We are using Hibernate Criteria. I haven't worked on Formulas and not sure if that would help solve the problem. It would be great if anyone can point me in the right direction. I appreciate that.

Thanks

Harish

3条回答
太酷不给撩
2楼-- · 2019-03-31 09:07

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

查看更多
混吃等死
3楼-- · 2019-03-31 09:15

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
查看更多
我想做一个坏孩纸
4楼-- · 2019-03-31 09:15

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

查看更多
登录 后发表回答