Let’s say I have entities A, B, C and each A has many B and C entities. I want to query a load of A entities based on some criterea, and I know I will be accessing all B and C entities for each A I return.
Something like select a from A as a join fetch a.b join fetch a.c would seem to make sense at first, but this creates a huge product if the numbers of B and C entities are large. Extending this to another associated entities makes the query totally unreasonable.
If I leave JPA to its own devices, I end up with n+1 selects when it wants to access the B and C entities.
What I thought I’d do was query A join fetch B, then A join fetch C, but this doesn’t work as it gives me two List<A> results each with only half the information.
This is a pretty simple query in SQL terms, and I’m disappointed there isn’t an obvious way to handle this. Am I missing something?
Provider is toplink essentials
I wonder why you say this is pretty simple in SQL terms. Wouldn’t you also have the cartesian product?
Using the Hibernate provider for JPA, an option you mention works:
You have two list of the same values, you use only one and it is fine (you just need to LEFT join).
In Hibernate, you can also ask to fetch the missing data in a second query.
Use
fetch="subselect".See https://www.hibernate.org/315.html
UPDATED after comment of the Original Poster:
In java, you could also do this by hand.
This would have a good performance also.
If you run several times into this need, you could write a parameterized method to do this for you, so you only code it once.