I am using the @OrderBy annotation in my entity class to sort a collection that is eagerly fetched. The column I am ordering on is of type String. However, in some instances, these strings may contain numbers. How do I ensure that the OrderBy annotation will order numbers stored as strings in their numeric order instead of 1,10,2,3,4,5,6,7,8,9 ?
2 Answers
@OrderBy
will sort according to the database since it will be part of your SQL query. Using @SortComparator with a custom comparator will achieve your result. You can also consider combining the 2 as well (@OrderBy so that you return in some consistent order from the database, then the @SortComparator for the desired order)
Not sure if you have an idea of how to write the comparator, but this question is a start to that.
-
Where `@SortComparable` come from? – wypieprz Apr 24 '14 at 10:37
-
Typo, it's meant to be @SortComparator .. updating my answer for this – Shiraaz.M Apr 24 '14 at 10:48
You may want to consider storing the strings as 0-prefix to a fixed maximum length, eg: 001, 023, 234 etc. Ordering will then work correctly using the normal string alpha comparison.
See Ordering results by computed value in Hibernate for a JPA specific implementation way of achiveing close to the same thing.
Another option is to store your collection in a TreeSet with a custom comparator.

- 1
- 1

- 1,689
- 1
- 11
- 13