Join fetch on nested collections

Hi,

I have an entity structure as follows:

E1
  List<E2> e2s; //OneToMany relation

E2
  E3 e3;
    E4 e4
      List<E5> e5s; //OneToMany relation

All the collections are lazy loaded by default. I’d like to define a JPA query to eager fetch the E5 list located in deeper levels of E1.

I tried queries like:

"SELECT e1 FROM E1 e1" +
            " LEFT JOIN FETCH e1.e2s AS e2s" +
            " JOIN e2s.e3 AS e3" +
            " JOIN FETCH e3.e4.e5s";

"SELECT e1 FROM E1 e1" +
            " LEFT JOIN FETCH e1.e2s AS e2s" +
            " JOIN e2s.e3.e4 AS e4" +
            " JOIN FETCH e4.e5s";

Results in query specified join fetching, but the owner of the fetched association was not present in the select list error.

"SELECT e1 FROM E1 e1" +
            " LEFT JOIN FETCH e1.e2s AS e2s" +
            " JOIN e2s.e3 AS e3" +
            " JOIN e3.e4.e5s";

This does not initialize the e5s collection.

Using Hibernate JPA 2.1.

Thanks in advance.

PS: The question is also available on Stackoverflow: https://stackoverflow.com/questions/64642399/join-fetch-for-nested-collections

You need to join fetch every association individually like this:

SELECT e1 
FROM E1 e1
LEFT JOIN FETCH e1.e2s AS e2Alias
JOIN FETCH e2Alias.e3 AS e3Alias
JOIN FETCH e3Alias.e4 AS e4Alias
JOIN FETCH e4Alias.e5s AS e5Alias