Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY using Criteria API

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"?

like image 682
niklassaers Avatar asked Nov 22 '09 21:11

niklassaers


People also ask

How do you use orderBy in CriteriaBuilder?

You can define an ORDER BY clause with the orderBy method of the CriteriaQuery interface and the asc or desc method of the CriteriaBuilder interface. The following CriteriaQuery returns Book entities in the ascending order of their title attribute. List<Book> books = em. createQuery(cq).

Which method can be used for ordering the result using criteria query?

The asc method is used to order the results by ascending value of the passed expression parameter.

What is the use of criteria API?

The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.


1 Answers

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(); 
like image 98
mR_fr0g Avatar answered Oct 09 '22 00:10

mR_fr0g