Java / JPA | 使用指定的inheritance类型进行查询
我正在构建一个通用表“Sample”的查询,我有几个类型inheritance自此表“SampleOne”,“SampleTwo”。 我需要一个像这样的查询:
select s from Sample where s.type = :type
其中type将是表的鉴别值。 是否有可能以任何方式(并避免创建特定于实体的查询,每个SampleOne,SampleTwo …等)
我将非常感谢本主题中的任何输入,
亲切的问候,P。
在JPA 2.0中,您可以使用TYPE
表达式(虽然目前它不适用于Hibernate中的参数,请参阅HHH-5282 ):
select s from Sample s where TYPE(s) = :type
类似的Hibernate特定表达式是.class
:
select s from Sample s where s.class = :type
以下是Java EE 6教程的相关部分 :
抽象实体
可以通过使用
@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; }
如果我读了这个,你的查询:
select s from Sample where s.type = :type
如果type
是鉴别器列,则只应返回指定子type
元素,因此您唯一要做的就是将结果列表转换为您请求的子类型。
你仍然需要谨慎使用Hibernate 4.3.7,因为TYPE()
的实现仍然存在问题,例如:
from SpoForeignPilot sfp where TYPE(sfp.partDocument) = :type
此查询不起作用,因为它错误地检查SpoForeignPilot
的类型而不是文档的类型。
您可以通过执行以下操作来解决此问题:
select sfp from SpoForeignPilot sfp join sfp.partDocument doc where TYPE(doc) = :type