Hibernate Tips: How to order the elements of a relationship

By Thorben Janssen

Association Mapping, Mapping, Query

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.

Question:

How can I order the elements of an annotate relationship without writing my own query?

Solution:

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!



Tags

Association Mapping, Mapping, Query


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Reply

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

    1. Hi Keerthi,

      Yes, it makes sense because the HashSet gets only used when you instantiate a new entity object. When you read it from the database, Hibernate uses its own Set implementation, which keeps the defined order.

      Regards,
      Thorben

  1. If the @OrderBy column is _not_ specified, will the association use one of the join columns to order by implicitly, or will the ordering of the result set potentially be non-deterministic?

    1. If you don’t specify the order, then it’s undefined. That means it depends on the internal implementation of your database and might not be deterministic.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}