0

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 ?

COBOL
  • 1,031
  • 8
  • 16
  • 32

2 Answers2

1

@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.

Community
  • 1
  • 1
Shiraaz.M
  • 3,073
  • 2
  • 24
  • 40
0

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.

Community
  • 1
  • 1
Craig Taylor
  • 1,689
  • 1
  • 11
  • 13