Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by discriminator value in table per class hierarchy mapping

Tags:

java

hibernate

Is it possible to write a HQL query that groups results by the discriminator value of a table per class hierarchy mapping? For instance

"select discriminator d, count(*) c from Foo group by discriminator"

with a mapping like

<hibernate-mapping>
  <class abstract="true" name="Foo">
    <!-- SNIP -->
    <subclass name="Bar" discriminator-value="BAR">
      <!-- SNIP -->
    </subclass>
    <subclass name="Baz" discriminator-value="BAZ">
      <!-- SNIP -->
    </subclass>
  </class>
</hibernate-mapping>

and a possible result like

+-----+---+
| d   | c |
+-----+---+
| BAR | 3 |
| BAZ | 4 |
+-----+---|

So what I'm looking for is a valid replacment for discriminator in my HQL query. Is there such as thing or do I have to go for raw SQL?

like image 885
sfussenegger Avatar asked Jun 25 '10 14:06

sfussenegger


People also ask

What is the additional tag we have to use under table per class inheritance mapping hierarchy?

You need to use @Inheritance(strategy=InheritanceType. SINGLE_TABLE), @DiscriminatorColumn and @DiscriminatorValue annotations for mapping table per hierarchy strategy. In case of table per hierarchy, only one table is required to map the inheritance hierarchy.

Is a mapping requires discriminator column?

So, you don't necessarily need a discriminator column. But let me start at the beginning. The SINGLE_TABLE strategy maps records from the same database table to different entity classes of an inheritance hierarchy. If you want to use this strategy with JPA, your database table needs to have a discriminator column.

Which inheritance mapping strategy uses discriminator column?

SINGLE_TABLE, all classes in the hierarchy are mapped to a single table in the database. This table has a discriminator column containing a value that identifies the subclass to which the instance represented by the row belongs.


1 Answers

The class attribute does that: from the Hibernate doc

The special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.

from Cat cat where cat.class = DomesticCat

Apparently it is necessary to use aliases to refer to your entities when using the class attribute, at least in the version of Hibernate I'm using. So your HQL request should be:

select f.class, count(*) c from Foo f group by f.class

And this will return arrays containing "BAR" and "BAZ" along with their respective counts.

like image 144
Guillaume Avatar answered Sep 17 '22 17:09

Guillaume