How to perform a non-polymorphic HQL query in Hibernate?
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:
- Manually filtering the instances after the query, OR: 开发者_StackOverflow社区
- Manually adding a WHERE clause on the discriminator column.
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!
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).
JPA 2 (Hibernate 3.5) adds support for non-polymorphic queries, this is very similar to Hibernates .class property (as Bozho answered above) but it is not Hibernate specific. This is done using the TYPE operator. As in
Select b from Book b where TYPE(b) = Book
You can read more about here it in my blog
Eyal
The ORM mimics the Java Model: if an object is an instance of another type (if an instance of PersianCat is an instance of Cat also), any query on Cat will have to be polymorphic (imagine you querying a List and asking if the entries match instanceof Cat
.
Even Bozho's solution is somewhat impure, since the 'class' column is supposedly opaque to your hibernate mapping, although I admit its a very good compromise. You can simply get the discriminator through the classe's simple name.
If you're comfy and are using table per class you can always do a native query to the Cat table to get the ids and then get the entries through hibernate.
Look at BaseQueryReturnFieldsCalculatorGC; it dynamically adds a condition to the 'where' which selects only where class=XXX; you can duplicate this logic to the HQLQueryTemplate and have the user define 'isNonPolymorphic'.
Note that it will only work with table-per-hierarchy, cos only then does the implicit class column exist and is selectable.
精彩评论