I have three entities: Person
, Country
and CountryTranslation
. Person
is related to one Country
and Country
have many CountryTranslations
.
I want my query to fetch both Country
and CountryTranslations
when it fetches a Person
in order to avoid multiple queries.
To bring the Country
along with Person
I do:
List<Person> persons = (List<Person>) entityManager
.createQuery("SELECT person from Person person " +
"left join fetch person.country")
.getResultList()
This works fine, I see on hibernate it is fetching nicely and no extra queries are executed to bring Country
, but to bring CountryTranslations
it still execute extra queries. Then I tried:
List<Person> persons = (List<Person>) entityManager
.createQuery("SELECT person from Person person " +
"left join fetch person.country " +
"left join fetch person.country.translations")
.getResultList()
And I get the error:
org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
What is the right way to do this fetching?
Thanks in advance
You correct this giving an alias for each relationship.
SELECT person
FROM person person
LEFT JOIN FETCH person.country country
LEFT JOIN FETCH country.translations
It's a framework's "limitation": When you use linked fetchs you should to give an alias for each relationship!
This behavior can also be explained because will be difficult to understand what these linked fetches really mean: Does the framework will fetch each relationship or only the last one? It's more simple to just tell to the framework what fetch relationship you want.