Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 422
Sandy Avatar asked Feb 07 '17 09:02

Sandy


1 Answers

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;
like image 150
Neil Stockton Avatar answered Nov 24 '22 01:11

Neil Stockton