Hibernate Criteria order by a specific state

2019-03-31 08:18发布

问题:

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

回答1:

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


回答2:

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



回答3:

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