JPA查询抽象类+子类字段条件

时间:2013-08-05 07:51:01

标签: inheritance jpa abstract

我有一个像这样的持久性模型:

@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;
}

我想向Employees查询一些子类条件,例如:salary> 1000。

我试过这个但没有工作。

SELECT e
FROM Employee e
WHERE e.salary > 1000;

SELECT e
FROM Employee e
WHERE (TYPE(e) = FullTimeEmployee AND e.salary > 1000)
OR TYPE(e) = PartTimeEmployee;

我还尝试在Employee中放置一个抽象方法,并在查询中使用它,但也没有工作。

你能帮我吗?

谢谢,

1 个答案:

答案 0 :(得分:9)

好的,我找到了解决方案。我不认为它是最好的,因为最终本机查询中的多次连接。但它正在发挥作用。

SELECT e
FROM Employee e, FullTimeEmployee f, PartTimeEmployee p
WHERE (e = f AND f.salary > 1000)
OR (e = p ...);

修改

找到另一个解决方案,其中 LOT 比上面的200k行更快。在where子句中使用嵌套选择:

SELECT e
FROM Employee e
WHERE e.employeeId IN (SELECT f.employeeId FROM FullTimeEmployee f WHERE f.salary > 1000)
OR e.employeeId IN (SELECT p.employeeId FROM PartTimeEmployee p WHERE ...)

<强>EDIT²:

似乎我不需要再加入最后一个版本的Hibernate(目前是4.3.10.Final)。

SELECT e
FROM Employee e
WHERE e.salary IS NULL
OR e.salary > 1000

应该有效