Java /JPA | Query with specified inherited type

redbull picture redbull · Feb 3, 2011 · Viewed 20.7k times · Source

I am building a query on a generic table "Sample" and I have several types which inherit from this table "SampleOne", "SampleTwo". I require a query like :

select s from Sample where s.type = :type

where type would be a discriminator value of the table. Is it possible in any way ( and avoid to create an entity specific queries, one for each SampleOne, SampleTwo... etc )

I would greatly appreciate any input in this topic,

Kind regards, P.

Answer

axtavt picture axtavt · Feb 3, 2011

In JPA 2.0 you can use TYPE expression (though currently it doesn't work with parameters in Hibernate, see HHH-5282):

select s from Sample s where TYPE(s) = :type

The similar Hibernate-specific expression is .class:

select s from Sample s where s.class = :type