Sorted collections in Hibernate
Problem
We want a collection field belonging to an entity object to be sorted.
Solution
There are two possible solutions:
- If you want the collection to be sorted when loaded, but not necessarily keep that sorting order all the time, use the
OrderByannotation where you set the actualORDER BYSQL clause. In that case, the collection can be of any type (e.g.Collection). If you want the collection to be sorted at all times, make it of type
SortedSetorSortedMapand set theSortannotation.- If the objects in the collection implements
Comparableset type toSortType.NATURAL. - Otherwise set it to
SortType.COMPARATORand specify your ownComparatorclass in thecomparatorattribute.
- If the objects in the collection implements
Remarks
- There exists an annotation with name
OrderByin both thejavax.persistencepackage as well as theorg.hibernate.annotationspackage. The former should be used.
There is a problem with the OrderBy annotation. If you overwrite the column name with @Column(name=”foo”) for the property bar, then bar is required in the orderby annotation. the sql code results in my case also in a …. order by bar …. statement. this fails.
MJ - October 24th, 2007 at 12:50Ah, I hadn’t stumbled upon that problem. Thanks for sharing!
Henrik Jernevad - October 24th, 2007 at 14:38