Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA query on abstract class + subclass field condition

I have a persistence model like this one :

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

I would like to query Employees with somes children class conditions, for example : salary > 1000.

I tried this but not working.

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;

I also tried to put an abstract method in Employee and use it in the query but not working either.

Could you help me please ?

Thanks,

like image 458
Ludovic Guillaume Avatar asked Aug 05 '13 07:08

Ludovic Guillaume


1 Answers

Ok, I found a solution. I don't think it is the best because of multiples joins in the final native query. But it is working.

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

EDIT:

Found another solution which is a LOT faster than the one above with 200k rows. Using nested selects in the where clause :

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²:

It seems that I don't need to do join anymore with last version of Hibernate (currently 4.3.10.Final).

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

should work

like image 76
Ludovic Guillaume Avatar answered Nov 12 '22 02:11

Ludovic Guillaume