From Clause
To retrieve all instances of a class with HQL, use the
from clause.
List<Continent> continents = session.createQuery("from Continent").list();
The 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:
select
CONT_ID,
CONT_NAME
from
CONTINENT
If there are classes with the same name in different packages, use a fully qualified name
to identify the correct one.
from levelup.world.hql.Continent
Where Clause
To return a subset of rows based on selection criteria, include the
where clause.
This is known as selection or restriction.
List<Continent> theAmericas = session.createQuery(
"from Continent where name like '%America%'")
.list();
This translates to the following SQL:
select
CONT_ID,
CONT_NAME
from
CONTINENT
where
CONT_NAME like '%America%'
Most of the common SQL expressions can also be found in
HQL.
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")
.list();
results in this SQL
select
CTRY_ID,
AREA,
CONT_ID,
CURRENCY,
CTRY_NAME,
POP,
POP_UPD_ON
from
COUNTRY
where
(
pop_upd_on is not null
or lower(ctry_name) in ('gabon' , 'gambia')
)
and (area between 100000 and 100000000)
Associations
We can also access entity associations in our query.
List<Country> africanCountries = session.createQuery(
"from Country where continent.name = 'Africa'")
.list();
The CONTINENT and COUNTRY tables are joined to produce the results.
select
COUNTRY.CTRY_ID,
COUNTRY.AREA,
COUNTRY.CONT_ID,
COUNTRY.CURRENCY,
COUNTRY.CTRY_NAME,
COUNTRY.POP,
COUNTRY.POP_UPD_ON
from
COUNTRY,
CONTINENT
where
COUNTRY.CONT_ID=CONTINENT.CONT_ID
and CONT_NAME='Africa'
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.
|