liveBook · Manning

Ordered set

As explained in Java Persistence with Spring Data and Hibernate epub

SortedSet is the Java collection interface for a set whose elements are ordered according to a specified comparator or their natural ordering.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains TreeSet initialization, natural or comparator sorting, in-memory loading behavior, and the database-ordering alternative.
Examples
Uses a persistent set of image filenames, natural String ordering, custom comparators, and LinkedHashSet database ordering.
What it assumes
Requires familiarity with Java collections, TreeSet, natural ordering, comparators, and persistence annotations.
What you can do after
Operate/configure a Hibernate SortedSet mapping and select between in-memory sorting and database ordering.
How it connects
Connects SortedSet with TreeSet, comparators, natural ordering, Hibernate collection loading, and SQL ORDER BY.

Also explained in

Compare how 3 books explain ordered set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.