We shall get all officers assigned to a starship by alphabetical order.
- implementing an HQL query with order by clause.
- using sort approach.
- using order approach.
Notice that now officers association is implemented using SortedSet instead of a List. Furthermore we are adding @Sort annotation to relationship, stating that officers should be natural ordered. Before finishing this post we will insist more in @Sort topic, but for now it is sufficient.
Obviously this method is not the best performance-way to sort a collection of elements. It is likely that we'll need a hybrid solution between using SQL clause and using annotation instead of writing a query.
And this leads us to explain the third possibility, using ordering approach.
Keep in mind that using javax.persistence.OrderBy allows us to specify the order of the collection via object properties, meanwhile org.hibernate.annotations.OrderBy order a collection appending directly the fragment of SQL (not HQL) to order by clause.
Now Officer class should not be touched, we don't need to implement compareTo method nor a java.util.Comparator. We only need to annotate officers field with @OrderBy annotation. Since in this case we are ordering by simple attribute, JPA annotation is used to maintain fully compatibility to other “JPA ready” ORM engines. By default ascendent order is assumed.
And if we rerun get all officers method, next queries are sent:
Furthermore OrderBy annotation does not force you to use SortedSet or SortedMap collection. You can use any collection like HashMap, HashSet, or even a Bag, because hibernate will use internally a LinkedHashMap, LinkedHashSet or ArrayList respectively.
I wish this post helped you to understand differences between "sort" and "order" in hibernate.