Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
How can I order the elements of an annotate relationship without writing my own query?
JPA supports the @OrderBy annotation which you can add to a relationship attribute as you can see in the following code snippet.
In this example, I want to order the Authors who have written a specific book by their last name. You can do this by adding the @OrderBy annotation to the relationship and specifying the ORDER BY statement in its value attribute. In this case, I define an ascending order for the lastName attribute of the Author entity.
If you want to order by multiple attributes, you can provide them as a comma-separated list as you know it from SQL or JPQL queries.
Hibernate uses the value of the annotation to create an ORDER BY statement when it fetches the related entities from the database.
Hibernate Tips Book
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.
Get it now!