12

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

Sandy
  • 547
  • 3
  • 9
  • 20

1 Answers1

26

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;
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
  • Thank you, but I'm not talking about a query but specifically about the annotation. I want the collection in the OneToMany sorted when it is fetched. – Sandy Feb 07 '17 at 09:09
  • I have tried that and I have a parse error when I deploy the application : "org.hibernate.HibernateException: Unable to parse order-by fragment". I'll update my post. – Sandy Feb 07 '17 at 09:18
  • Well that is what the JPA spec defines, and what the JPA provider I use accepts, so suggest that you raise an issue on your JPA provider – Neil Stockton Feb 07 '17 at 09:19
  • Turns out the problem was caused by the antlr dependency which I had to exclude. I accepted your answer anyway as I was hunting around for the confirmation that the syntax was indeed correct. – Sandy Feb 07 '17 at 10:06