bob-cac
bob-cac

Reputation: 1302

JPA inheritance query (Eclipse Link)

Consider the following schema:

public class A {
    @Id
    int id;
    String fieldA;
}
public class B extends A {
    String fieldB;
}
public class C extends A {
    String fieldC;
}

How can I query A in such a way to get all the C's and get only the B's where fieldB="someValue"?

I have tried to use treat in order to make downcast but it seems that the filter on B is working on all the parent class (A).

Is such query possible in the first place?

Upvotes: 0

Views: 123

Answers (1)

JeroenS
JeroenS

Reputation: 56

You can create a query with the 'type' keyword to filter by type and an exists subquery to filter the C entities:

select a
from A a
where type(a) = :type
or exists (
  select 1
  from B b
  where b.id = a.id
  and b.fieldB = :fieldB
)

The class type of entity C is passed by invoking the setParameter method of the query instance.

Upvotes: 2

Related Questions