Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java /JPA | Query with specified inherited type

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.

like image 718
redbull Avatar asked Feb 03 '11 09:02

redbull


2 Answers

Here's the relevant section of the Java EE 6 tutorial:

Abstract Entities

An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities are like concrete entities but cannot be instantiated.

Abstract entities can be queried just like concrete entities. If an abstract entity is the target of a query, the query operates on all the concrete subclasses of the abstract entity:

@Entity
public abstract class Employee {
    @Id
    protected Integer employeeId;
    ...
}
@Entity
public class FullTimeEmployee extends Employee {
    protected Integer salary;
    ...
}
@Entity
public class PartTimeEmployee extends Employee {
    protected Float hourlyWage;
}

If I read this right, your query:

select s from Sample where s.type = :type

Should only return elements of the specified subtype if type is the discriminator column, so the only thing that's left for you to do is to cast the result list to your requested sub type.

like image 71
Sean Patrick Floyd Avatar answered Oct 17 '22 20:10

Sean Patrick Floyd


You still have to be carefull in Hibernate 4.3.7, because there is still an issue with the implementation of TYPE(), for example:

from SpoForeignPilot sfp where TYPE(sfp.partDocument) = :type

This query doesn't work as it incorrectly checks the type of SpoForeignPilot and not the type of the document.

You can workaround this issue by doing something like this:

select sfp from SpoForeignPilot sfp join sfp.partDocument doc where TYPE(doc) = :type
like image 24
Wim De Rammelaere Avatar answered Oct 17 '22 19:10

Wim De Rammelaere