Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 389
Eli Acherkan Avatar asked Jan 19 '10 11:01

Eli Acherkan


People also ask

Does HQL support polymorphic queries?

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.

What is polymorphic queries in hibernate?

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.

Is JPQL and HQL same?

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.


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

like image 90
Rob H Avatar answered Sep 21 '22 06:09

Rob H


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

like image 34
Bozho Avatar answered Sep 21 '22 06:09

Bozho