JPA request for abstract class + subclass field condition

I have a persistence model similar to this:

@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 request Employees with somes children class conditions, for example: pay> 1000.

I tried this but did not work.

 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 apply the abstract method in Employee and use it in the query, but it does not work.

could you help me?

Thanks,

+6
source share
1 answer

Ok, I found a solution. I do not think this is the best due to multiple joins in the final native query. But it works.

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

EDIT:

Found another solution that is LOT faster than higher, with 200k lines. Using nested selections 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 I no longer need to join the latest version of Hibernate (currently 4.3.10.Final).

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

must work

+9
source

Source: https://habr.com/ru/post/951020/


All Articles