Search code examples
javajpajoineclipselinkjpql

JPQL Join over several connected Entities


I have the following entity structure (Pseudo)

class A 
@OneToMany      
List<B> bList;      

class B
@ManyToOne
A aFk;
@OneToMany
List<C> cList;

class C
@ManyToOne
B bFk;
@ManyToOne
D dFk;

class D
@OneToMany
List<C> cList;

I want to retrieve all D entities but I have only the entity A from the client.

I want to start with A and iterate through the relationships to B. And select those that match the A property in where clause.

How can I perform this with JPQL ? Is the query easier with CriteriaAPI?

I tried it with jpql but it retrieves all D entities.

Select distinct d
from A a, D d
join a.bList ab
join ab.cList
join d.cList cd
where a.name='A'

I use EclipseLink


Solution

  • You don't use the association between C and D in your query. It should simply be

    select distinct d from A a
    join a.bList b
    join b.cList c
    join c.dFk d
    where a.name = 'A'