Hibernate Query Language (HQL) Order By Examples

This post shows how to do sorting using HQL in Hibernate application.

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turn perform an action on a database.

Sorting with HQL

Example 1: Simple HQL Order By Example

Sorting with Hibernate's HQL is as simple as adding the Order By clause to the HQL query string:
String hql = "FROM Foo f ORDER BY f.name";
Query query = sess.createQuery(hql);

Example 2: Using an Explicit Sorting Order

To specify the sorting order manually – you'll need to include the order direction in the HQL query string:
String hql = "FROM Foo f ORDER BY f.name ASC";
Query query = sess.createQuery(hql);

Example 3: Sorting by More Than One Attribute

Multiple attributes, together with an optional sorting order, can be added to the Order By clause in the HQL query string:
String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC";
Query query = sess.createQuery(hql);

Comments