jpa – JPQL exclude subclasses in a query – Education Career Blog

If I have a class Apple that extends Fruit, how do I write a JPQL query to return all objects that are strictly Fruits and not Apples?


This is possible in JPA 2.0 using the TYPE operator. From the JPA 2.0 specification: Entity Type Expressions

An entity type expression can be used
to restrict query polymorphism. The
TYPE operator returns the exact type
of the argument.

The syntax of an entity type
expression is as follows:

entity_type_expression ::=
        type_discriminator |
        entity_type_literal |
type_discriminator ::=
        TYPE(identification_variable |
             single_valued_object_path_expression |
             input_parameter )

An entity_type_literal is
designated by the entity name.

The Java class of the entity is used
as an input parameter to specify the
entity type.

So you could do something like this:

FROM Fruit f
WHERE TYPE(f) <> Apple

But this is not available in JPA 1.0 and if you are using JPA 1.0, you’d have to rely on a provider specific extension (please mention your provider in that case).


  • JPA 2.0 Specification
    • Section 4.4.8 “Polymorphism”
    • Section “Entity Type Expressions”

Leave a Comment