Search code examples
hibernatenhibernatetypeshql

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?


Solution

  • 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