To retrieve all instances of a class with HQL, use the
List<Continent> continents = session.createQuery("from Continent").list();
List (which uses generics to demonstrate the return type) is populated with an
instance of the
Continent class for each row returned by this SQL query:
If there are classes with the same name in different packages, use a fully qualified name
to identify the correct one.
To return a subset of rows based on selection criteria, include the
This is known as selection or restriction.
List<Continent> theAmericas = session.createQuery(
"from Continent where name like '%America%'")
This translates to the following SQL:
CONT_NAME like '%America%'
Most of the common SQL expressions can also be found in
For example, this HQL
List<Country> countries = session.createQuery(
"from Country " +
"where (populationUpdatedOn is not null " +
"or lower(name) in ('gabon', 'gambia')) " +
"and area between 100000 AND 100000000")
results in this SQL
pop_upd_on is not null
or lower(ctry_name) in ('gabon' , 'gambia')
and (area between 100000 and 100000000)
We can also access entity associations in our query.
List<Country> africanCountries = session.createQuery(
"from Country where continent.name = 'Africa'")
The CONTINENT and COUNTRY tables are joined to produce the results.
The HQL query in this example uses implicit association joining (i.e. the join is not specified in full)
which is available for many-to-one and one-to-one associations.
This syntax is convenient but can be confusing if many associations are accessed in the query,
as the underlying joins are not obvious. The preferred method for more complex queries
is to use explicit join syntax.