An ordered set uses SortedSet with TreeSet to maintain unique elements in stable order. Hibernate sorts the elements in memory after loading them, using natural ordering or a Java Comparator. section 8.1.3 section 8.1.8
Choose an ordered set when:
- Elements must remain unique and iteration order must be stable. section 8.1.3
- Natural ordering is sufficient, as with String#compareTo(), or a custom Comparator defines the required order. section 8.1.8
- Sorting after database loading is acceptable; use a LinkedHashSet with Hibernate @OrderBy when the database should produce the order instead. section 8.1.8
Naturally sorted persistent set
@ElementCollection @CollectionTable(name = "IMAGE") @Column(name = "FILENAME") @org.hibernate.annotations.SortNatural private SortedSet<String> images = new TreeSet<>(); @SortNatural enables natural String ordering while the TreeSet supplies the Java collection implementation. A custom ordering can instead use Hibernate's @SortComparator with a Comparator implementation. section 8.1.8
Listing 8.8 Sorting set elements in memory with String#compareTo()
Path: Ch08/mapping-collections/src/main/java/com/manning/javapersistence /ch08/sortedsetofstrings/Item.java @Entity public class Item { // . . . @ElementCollection @CollectionTable(name = "IMAGE") @Column(name = "FILENAME") @org.hibernate.annotations.SortNatural private SortedSet<String> images = new TreeSet< >();
Shows the complete entity-field mapping for a naturally sorted SortedSet of strings. section 8.1.8


