persistence@glassfish.java.net

JPQL and Inheritance

From: Shelley <randomshelley_at_gmail.com>
Date: Fri, 19 Oct 2007 18:21:46 -0500

I have an abstract entity class which defines a joined inheritance type,
using a discriminator column. I would like to create a JPQL query which
allows for dynamic inclusion/exclusion of specific entity subtypes.

@Entity(name = "ABSTRACT_ENTITY")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "ABSTRACT_ENTITY_TYPE", discriminatorType =
DiscriminatorType.STRING)
public abstract class AbstractEntity {
  . . .
}

@Entity(name = "ENTITY_SUB_A")
@DiscriminatorValue(value = "discrimatorValueA")
public class SubEntityA {
  . . .
}

@Entity(name = "ENTITY_SUB_B")
@DiscriminatorValue(value = "discrimatorValueB")
public class SubEntityB {
  . . .
}

Essentially what I want to do is:
   "SELECT DISTINCT e FROM ABSTRACT_ENTITY e WHERE e.ABSTRACT_ENTITY_TYPE =
'discrimatorValueA' OR e.ABSTRACT_ENTITY_TYPE = 'discrimatorValueD' ..."
 OR
   "SELECT DISTINCT e FROM ABSTRACT_ENTITY e WHERE e.ABSTRACT_ENTITY_TYPE <>
'discrimatorValueA' ..."
 (The specific WHERE clause will be variable; it may contain multiple
conditional expressions, etc.)

Since the discriminator column is only related to the physical schema, and
is not declared as a property of the logical entity, querying for
abstractEnity.ABSTRACT_ENTITY_TYPE is not possible in JPQL. I can create
the query using native SQL, but I'd prefer to remain independent of native
queries; or a property could be added to the subclass to uniquely identify
it (essentially mimicking the discriminatorColumn), but this results in
unnecessary duplication, leaking an unnecessary property which is only
needed for JPA.

Are there any other suggestions on how to restrict JPQL query results based
on subclass?