A mapped collection can be sorted in memory with a Java comparator or loaded in database order with SQL ORDER BY. These approaches affect how elements are ordered, not the database schema. section 8.1.8
Choose the ordering strategy to match the collection and where sorting should happen:
- Use SortedMap with a Hibernate comparator for custom in-memory order, or SortedSet with natural ordering such as String.compareTo(). section 8.1.8
- Use a collection with stable iteration order, such as LinkedHashSet, and Hibernate @OrderBy to retrieve elements in SQL order. Standard JPA @OrderBy works for a column with ASC or DESC. section 8.1.8
- A bag cannot be sorted in memory; use SQL ordering when database retrieval order is required. section 8.1.8
Listing 8.7 Sorting map entries in memory using a comparator
Path: Ch08/mapping-collections/src/main/java/com/manning/javapersistence /ch08/sortedmapofstrings/Item.java @Entity public class Item { // . . . @ElementCollection @CollectionTable(name = "IMAGE") @MapKeyColumn(name = "FILENAME") @Column(name = "IMAGENAME") @org.hibernate.annotations.SortComparator(ReverseStringComparator.class) private SortedMap<String, String> images = new TreeMap<>();
Example mapping a SortedMap with a comparator that sorts string keys in reverse order. section 8.1.8
