lishman levelup
«previous  next»

Getting Started

Hibernate Query Language API


A Query object, which represents an HQL query, is created from the current session.
Query hqlQuery = session.createQuery("from Continent");
No SQL is executed by this statement.


The list() method executes the SQL and processes the results.
List<Continent> continents = hqlQuery.list();
In this example, Hibernate instantiates and populates a Continent object for each row returned and stores the results in a java.util.List. All rows are retrieved and the entire result set is stored in memory.

Note that all the other examples in this section use method chaining to combine the createQuery() and list() methods into a single statement.

Single Instance

To return a single instance only, use the unqueResult() method instead of list().
Continent antarctica = (Continent) session.createQuery(
       "from Continent where id = 7")
A null is returned if no rows are found and an exception is thrown if more then one row matches the selection criteria.

One way to guarantee that at most one row is returned is to set the maximum results to one.
Country highestPopulation = (Country) session.createQuery(
      "from Country order by population desc")
This time, all the countries are ordered by population (largest first) and only the first instance is returned.

The order by clause in HQL uses the same syntax as SQL.
List<Country> countries = session.createQuery(
      "from Country order by area desc, name")
This query sorts the results into ascending (the default) name within descending area.


setMaxResults() can be combined with setFirstResult() to provide pagination on the result set.
List<Country> page3 = session.createQuery(
     "from Country order by name")
This query will skip four rows and then get the next two, using this SQL:
  ( select
    rownum rownum_
    ( select
    order by
      CTRY_NAME ) row_
    rownum <= ?
  rownum_ > ?
Oracle uses the rownum pseudocolumn to select the required rows. Hibernate will apply the appropriate technique for offsetting and limiting the result set depending on the SQL dialect specified in the Hibernate configuration file.

The order by clause is included to guarantee that the results are in the same order each time the query is executed.

Named Query

Rather than embed an HQL statement directly in a createQuery() method, we can set up a named query. This externalizes the query string from the code which improves maintainability.

For example, to get the most populous countries we define this named query:
@NamedQueries ({
  name = "mostPopulous",
  query = "from Country where population > 10000000 order by population desc")

public class Country {
Although the named query is defined on the Country class, it has global scope and can be accessed by any class from the current session. Use the getNamedQuery() method to access the query.
List<Country> mostPopulous = session.getNamedQuery("mostPopulous").list();