I have a complex class hierarchy with multiple levels of inheritance, and I need to query for certain specific types within that hierarchy, using HQL.
Let's say I have classes Cat, Dog and Monkey, with a common base-class Animal.
How do I write a query that selects only some of those, let's say, Cat and Dog?
I also need to sort or filter by certain Animal properties - so let's say, animals with Sex="Male" and order by Name.
Is this possible?
A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed. Note that HQL subqueries can occur only in the select or where clauses.
The HQL Group By clause is used to group the data from the multiple records based on one or more column. It is generally used in conjunction with the aggregate functions (like SUM, COUNT, MIN, MAX and AVG) to perform an aggregation over each group.
Supports polymorphic queries. Polymorphic queries return the query results along with all the child objects (objects of subclasses), if any. Easy to learn and use. The syntax of HQL is quite similar to that of SQL This makes Hibernate queries easy to learn and implement in the applications.
Hibernate Query Language (HQL) supports various aggregate functions – min(), max(), sum(), avg(), and count() in the SELECT statement. Just like any other SQL keyword, usage of these functions is case-insensitive.
The standard JPQL function is TYPE()
, that supported in Hibernate as well, as mentioned in its documentation.
Please, follow an example:
select a from Animal a
where type(a) in ('Cat', 'Dog')
and a.sex = 'Male'
order by a.name
Hibernate also uses the .class
implicit property:
select a from Animal a
where a.class in ('Cat', 'Dog')
and a.sex = 'Male'
order by a.name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With