ORDER BY using Criteria API

niklassaers picture niklassaers · Nov 22, 2009 · Viewed 173.7k times · Source

When I write a HQL query

Query q = session.createQuery("SELECT cat from Cat as cat ORDER BY cat.mother.kind.value");
return q.list();

Everything is fine. However, when I write a Criteria

Criteria c = session.createCriteria(Cat.class);
c.addOrder(Order.asc("mother.kind.value"));
return c.list();

I get an exception org.hibernate.QueryException: could not resolve property: kind.value of: my.sample.data.entities.Cat

If I want to use Criteria and Order, how should I express my "order by"?

Answer

mR_fr0g picture mR_fr0g · Nov 22, 2009

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();