Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove order from Hibernate Criteria?

If I have an @OrderBy("someProperty") annotation on an object and then use a Criteria to add an ORDER BY clause like so:

criteria.addOrder(Order.asc("id"));

The resulting SQL will do the ordering like this:

ORDER BY someProperty, id asc

Is it possible to change the order of the two or to remove the someProperty order? I can't remove the @OrderBy annotation and I'm using Hibernate for Java.

like image 743
Jörgen Lundberg Avatar asked Sep 21 '10 09:09

Jörgen Lundberg


People also ask

How can add order by criteria in Hibernate?

Add an ordering to the result set. Join an association, assigning an alias to the joined association. Join an association using the specified join-type, assigning an alias to the joined association. Create a new Criteria, "rooted" at the associated entity.

Can we use order by 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.

What is restriction in Hibernate criteria?

1.2. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method. This method takes an org. hibernate.

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.


2 Answers

Criteria has no methods for removal of Order neither Criterion Order class is very limited, you can only use property names and it generates standard and portable SQL. OrderBy annotation is a SQL order, as javadoc states: OrderBy That means you can use there any sql (even a exclusive one of your database vendor). Take a look at these article: Sorting Collections in Hibernate Using SQL in @OrderBy

Adding a SQL fragment into your domain class isn't necessarily the most elegant thing in the world, but it might be the most pragmatic thing.

like image 172
Awi Avatar answered Sep 17 '22 04:09

Awi


It may be possible to remove particular ordering via criteria.iterateOrderings() iterator, but I'm not sure how it works with annotations.

like image 32
mailgpa Avatar answered Sep 21 '22 04:09

mailgpa