Hibernate supports collections implementing
java.util.SortedMap and java.util.SortedSet. You must specify a comparator in the mapping file:
<set name="aliases"
table="person_aliases"
sort="natural">
<key column="person"/>
<element column="name" type="string"/>
</set>
<map name="holidays" sort="my.custom.HolidayComparator">
<key column="year_id"/>
<map-key column="hol_name" type="string"/>
<element column="hol_date" type="date"/>
</map>
Allowed values of the
sort attribute are unsorted, natural and the name of a class implementing java.util.Comparator.
Sorted collections actually behave like
java.util.TreeSet or java.util.TreeMap.
If you want the database itself to order the collection elements, use the
order-by attribute of set, bag or map mappings. This solution is only available under JDK 1.4 or higher and is implemented using LinkedHashSet or LinkedHashMap. This performs the ordering in the SQL query and not in the memory.
<set name="aliases" table="person_aliases" order-by="lower(name) asc">
<key column="person"/>
<element column="name" type="string"/>
</set>
<map name="holidays" order-by="hol_date, hol_name">
<key column="year_id"/>
<map-key column="hol_name" type="string"/>
<element column="hol_date type="date"/>
</map>Note
The value of the
order-by attribute is an SQL ordering, not an HQL ordering.
Associations can even be sorted by arbitrary criteria at runtime using a collection
filter():
sortedUsers = s.createFilter( group.getUsers(), "order by this.name" ).list();