I'm using Hibernate 3.1.1, and in particular, I'm using HQL queries.
According to the documentation, Hibernate's queries are polymorphic:
A query like:
from Cat as cat
returns instances not only ofCat
, but also of subclasses likeDomesticCat
.
How can I query for instances of Cat, but not of any of its subclasses?
I'd like to be able to do it without having to explicitly mention each subclass.
I'm aware of the following options, and don't find them satisfactory:
It would make sense for Hibernate to allow the user to decide whether a query should be polymorphic or not, but I can't find such an option.
Thanks in advance!
HQL supports polymorphism as well as associations, which in turn allows developers to write queries using less code as compared to SQL. In addition, HQL supports many other SQL statement and aggregate functions, such as sum() and max() and clauses, such as group by and order by.
A polymorphic query is one were we can query on the Parent class and as a result get instances of Parent, LeftChild and RightChild. If we set up the descriptor to support polymorphic queries then the following query will return instances of all Parent, LeftChild and RightChild objects stored in the database.
The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.
Use polymorphism="explicit"
in the class mapping. This will cause queries to return only instances of the named class and not its subclasses.
Implicit polymorphism means that instances of the class will be returned by a query that names any superclass or implemented interface or class, and that instances of any subclass of the class will be returned by a query that names the class itself. Explicit polymorphism means that class instances will be returned only by queries that explicitly name that class.
SELECT cat FROM Cat cat WHERE cat.class='cat'
where the value 'cat'
is the discriminator value of the Cat
class.
If you are using TABLE_PER_CLASS
, then try cat.class='Cat'
) (the name of the class)
This is not exactly a where clause on the discriminator column, because such a query will fail (the discriminator column is available only in native queries).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With