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 OrderBy annotation where you set the actual ORDER BY SQL 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 SortedSet or SortedMap and set the Sort annotation.

    • If the objects in the collection implements Comparable set type to SortType.NATURAL.
    • Otherwise set it to SortType.COMPARATOR and specify your own Comparator class in the comparator attribute.

Remarks

  • There exists an annotation with name OrderBy in both the javax.persistence package as well as the org.hibernate.annotations package. The former should be used.

See also

2 Responses

  1. 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:50
  2. Ah, I hadn’t stumbled upon that problem. Thanks for sharing!

    Henrik Jernevad - October 24th, 2007 at 14:38