liveBook · Manning

Sorted collection

As explained in Java Persistence with Spring Data and Hibernate epub

A sorted collection is a collection whose elements are maintained or presented according to an ordering relation.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains comparator-based and natural sorting, SQL ordering, and the bag limitation without detailing implementation internals.
Examples
Maps image filenames and names, demonstrating reverse string-key order, natural string order, and descending filename order.
What you can do after
Operate/configure collection mappings to sort in memory or load elements in SQL order.
How it connects
Connects Java Comparator, SortedMap, SortedSet, LinkedHashSet, and SQL ORDER BY.

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.