Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria Order By

I have a table called Gift, which has a one-to-many relationship to a table called ClickThrough - which indicates how many times that particular Gift has been clicked. I need to query for all of the Gift objects, ordered by ClickThrough count. I do not need the ClickThrough count returned, as I don't need anything done with it, I just want to use it for purposes of ordering.

I need the query to return a List of Gift objects directly, just ordered by ClickThrough count. How do I do this using the Criteria API? I can find a lot of documentation out there on similar information to this, but nothing quite like what I need.

like image 890
Dustin Wilhelmi Avatar asked Feb 25 '11 01:02

Dustin Wilhelmi


People also ask

How do you add an order by criteria?

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).

Is order by supported in HQL?

Order by orders the data on the basis of given property in ascending or descending order. Group by groups the data on the basis of given property. In HQL we perform order by and group by for the given property of entity or associated entities.

Which is sorted in normal order in hibernate?

The Order class has two methods to set the sorting order: asc(String attribute) : Sorts the query by attribute in ascending order. desc(String attribute) : Sorts the query by attribute in descending order.

What is Hibernate Criteria query?

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.


1 Answers

Note for anyone else that comes through here looking to order by a property/column:

When using the approaches mentioned here, no results were found. The fix was to use criteria.addOrder(Order.asc(property)); instead. Notice the difference is to use addOrder, rather than add;

I've had this issue several times after running here for a quick reference.

like image 194
musicin3d Avatar answered Sep 25 '22 08:09

musicin3d