liveBook · Manning

JPA @OrderBy annotation

As explained in Java Persistence with Spring Data and Hibernate epub

The JPA @OrderBy annotation specifies ordering of elements in a persistent collection using entity properties or basic-element values.

JPA @OrderBy applies database load-time ordering to elements in a persistent collection. Its value names persistent properties followed by ASC or DESC; ascending order is the default. Multiple properties provide tie-breaking order. section 8.2.2

Ordering embeddable images

For an element collection of Image components, order images by filename descending and then width descending while retaining that order during iteration: @ElementCollection @CollectionTable(name = "IMAGE") @OrderBy("filename DESC, width DESC") private Set<Image> images = new LinkedHashSet<>(); The persistence provider uses the properties of Image to construct the collection-loading order. LinkedHashSet preserves the resulting iteration order. section 8.2.2

Choose the ordering annotation according to the collection element and the required expression:

  • Use JPA @OrderBy with entity or embeddable properties, such as filename DESC, width DESC. section 8.2.2
  • Use JPA @OrderBy on basic-element collections to order by the element value; only the direction can change because basic values have no properties. section 8.1.8
  • Use Hibernate’s @org.hibernate.annotations.OrderBy when the ordering requires a SQL fragment or database function; this sacrifices the JPA property-based form. section 8.1.8
  • Pair ordering with an iteration-stable collection such as LinkedHashSet or ArrayList when callers must observe the loaded order. section 8.1.8

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains property syntax, defaults, basic-value limits, stable iteration, and Hibernate SQL alternatives, but not provider execution internals.
Examples
Demonstrates Image collections ordered by filename and width, plus basic String collections ordered by their stored values.
What it assumes
Assumes Java collection mappings and persistent properties, while distinguishing basic elements from embeddable or entity elements.
What you can do after
Apply it via JPA mappings to return collections in property-based order while preserving that order through suitable collection implementations.
How it connects
Connects collection mappings with embeddable components, LinkedHashSet, ArrayList, SQL ORDER BY, and Hibernate-specific ordering.

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.