Sorting @OneToMany collections in Hibernate

Posted on 31-01-2013 20:27 by graham
This tutorial shows how to sort @OneToMany collections in Hibernate.

Using the @OrderBy annotation

If you have a collections of some objects annotated with @OneToMany, all you need to do to have it sorted it to make use of the @OrderBy annotation (javax.persistence.OrderBy).
@OneToMany(mappedBy = "parent")
public List<Person> getChildren()
return this.children;

Once the collection is annotated this way, Hibernate will build its queries in a way that includes ordering of items.

Using Lists instead of Sets

When using this solution, be sure to have the getter of the collection you want to sort return List type. Do not use Set, because it does not support order, so even if your Hibernate query will return ordered items, there is no guarantee this order will be preserved.


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems