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

Viewed 15315

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 of Cat, but also of subclasses like DomesticCat.

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:

  1. Manually filtering the instances after the query, OR:
  2. 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!

5 Answers

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

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.

Related