JPA/Hibernate @OrderBy annotation with multiple columns and ASC/DESC for each

Sandy picture Sandy · Feb 7, 2017 · Viewed 17k times · Source

I would like to sort a OneToMany field with the @OrderBy annotation with multiple columns and specify the sort order for each but I can't seem to find the info anywhere on whether how to or if it's impossible. The specs for the annotation says:

orderby_list::= orderby_item [,orderby_item]*
orderby_item::= property_or_field_name [ASC | DESC]

so my guess is it's not possible but I prefer to ask anyway.

Putting the following throws a HibernateException on deployment :

@OrderBy("field1 DESC, field2 DESC, field3 DESC, field4 DESC")

Generating :

Caused by: org.hibernate.HibernateException: Unable to parse order-by fragment

Thanks

Answer

Neil Stockton picture Neil Stockton · Feb 7, 2017

If you have a class Person with 2 fields, firstName and lastName then with a query you can do

SELECT p FROM Person p ORDER BY p.firstName ASC, p.lastName DESC

which is what the JPQL BNF says.

In terms of when you have a List of Person objects, you can define the List ordering like this (same syntax)

@OneToMany
@OrderBy("firstName ASC, lastName DESC")
List<Person> myList;