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
