Over a million developers have joined DZone.

Hibernate Tips: How to Order the Elements of a Relationship

DZone 's Guide to

Hibernate Tips: How to Order the Elements of a Relationship

Having trouble figuring out how to order elements of an annotated relationship without writing your own query? Read this tutorial to find a solution.

· Database Zone ·
Free Resource

Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. Some of the most popular tips are also available as a book.

If you have a question for a future Hibernate Tip post, please leave a comment below.


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

Get more videos from the Hibernate Tips playlist.


JPA supports the @OrderBy annotation, which you can add to a relationship attribute as you can see in the following code snippet.

joinColumns={@JoinColumn(name="bookId", referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="authorId", referencedColumnName="id")})
@OrderBy(value = "lastName ASC")
private Set<Author> authors = new HashSet<Author>();

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.

05:22:13,930 DEBUG [org.hibernate.SQL] – 
select authors0_.bookId as bookId1_2_0_, 
    authors0_.authorId as authorId2_2_0_, 
    author1_.id as id1_0_1_, 
    author1_.firstName as firstNam2_0_1_, 
    author1_.lastName as lastName3_0_1_, 
    author1_.version as version4_0_1_ 
from BookAuthor authors0_ inner join Author author1_ 
    on authors0_.authorId=author1_.id 
where authors0_.bookId=? 
order by author1_.lastName asc
java ,java ee ,hibernate ,relational ,tips ,tutoiral

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}