How to perform a non-polymorphic HQL query in Hibernate?

Solution 1:

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.

Solution 2:

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

Solution 3:

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

Solution 4:

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.