Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

MariaDB TX, proven in production and driven by the community, is a complete database solution for any and every enterprise — a modern database for modern applications.

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.

Question:

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

Get more videos from the Hibernate Tips playlist.

Solution:

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

@ManyToMany
@JoinTable(name="BookAuthor",
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

MariaDB AX is an open source database for modern analytics: distributed, columnar and easy to use.

Topics:
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 }}