Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL query for multiple types/classes

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?

like image 593
mindplay.dk Avatar asked Jan 18 '12 14:01

mindplay.dk


People also ask

How do I write a subquery in HQL?

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.

Can we use group by in HQL?

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.

Does HQL support polymorphic queries?

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.

Does HQL support aggregate functions?

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.


1 Answers

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
like image 84
JB Nizet Avatar answered Sep 21 '22 02:09

JB Nizet