hibernate order by association

10,397

Solution 1

Ok, found the answer. I tried something that I didn't think would work, but to my surprise did. I was trying this:

Criteria criteria = super.getSession().createCriteria(WipDiscreteJob.class);

criteria.addOrder(Order.asc("assnName.propertyName"))

but what actually worked was:

Criteria criteria = super.getSession().createCriteria(WipDiscreteJob.class);
Criteria assnCrit = criteria.createCriteria("assnName");

assnCrit.addOrder(Order.asc("propertyName"));

I had made the assumption that the addOrder() method was only usable on the main criteria and not on any association criteria.

Solution 2

I was having the same issue and it can also be solved like this:

Criteria criteria = super.getSession().createCriteria(WipDiscreteJob.class)
  .createAlias("assnName","a")
  .addOrder(Order.asc("a.propertyName"));

createAlias lets you keep your criteria rooted on your original entity (WipDiscreteJob.class in this case) so that you can keep building your criteria up in case you needed it (for example, if you need a second order by property from you original entity).

Share:
10,397

Related videos on Youtube

Gary Kephart
Author by

Gary Kephart

I'm a Java software engineering lead who works with the full SDLC, from planning, requirements gathering, development and testing to production support. I'm a full stack developer, capable of creating web pages and Swing apps as well as working with JPA and databases.

Updated on May 24, 2020

Comments

  • Gary Kephart
    Gary Kephart almost 4 years

    I'm using Hibernate 3.2, and using criteria to build a query. I'd like to add and "order by" for a many-to-one association, but I don't see how that can be done. The Hibernate query would end up looking like this, I guess:

    select t1.a, t1.b, t1.c, t2.dd, t2.ee
    from t1
    inner join t2 on t1.a = t2.aa
    order by t2.dd   <-- need to add this
    

    I've tried criteria.addOrder("assnName.propertyName") but it doesn't work. I know it can be done for normal properties. Am I missing something?

  • Abdullah Jibaly
    Abdullah Jibaly over 12 years
    Was looking all over for this, thanks! You can even do .createAlias("assnName", "assnName") which allows you to keep the same syntax as HQL.
  • Marcelo
    Marcelo over 12 years
    @Abdullah Glad to be able to help.
  • smp7d
    smp7d over 12 years
    This was very helpful. It took awhile to find this.

Related