tags:

views:

14

answers:

1

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?

+1  A: 

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

4.6.17.4 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 |
        input_parameter
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:

SELECT f
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).

References

  • JPA 2.0 Specification
    • Section 4.4.8 "Polymorphism"
    • Section 4.6.17.4 "Entity Type Expressions"
Pascal Thivent