Search code examples
javaeclipselink

Filter using field from child entity


I have class Person containing field age, Class Student extends Person containing field class, and class Teacher extends Person and containing field salary.

I want to get all Person who are in class X, if they are Student, and earn 1500$, if they are Teacher, using the same jpql query. The query must return a list of Person. I can make two query and make a method that call both query and join the result but is there a better solution.

I hope I was able to explain


Solution

  • Use "TYPE" and JPA 2.1 "TREAT" to filter on the class.

    "SELECT p from Person p where treat(p as Teacher).salary = 1500 or TYPE(p) = Student"
    

    If you cannot use JPA 2.1, you can use a subquery on Teacher to return Teacher ids with salary=1500, and use the result in the main query.

    "SELECT p from Person p where p.id in(SELECT t.id from Teacher t where t.salary=1500) or TYPE(p) = Student"