Lazily fetched child collections are fetched fully when being navigated. More, if you have a parent entity, you need to run a query to fetch all child entity identifiers.
Quote:
I assume the child entity id is fetched when fetching the parent entity.
That's not true. The child side @ManyToOne association is a FK to the parent entity PK. If you only fetch the parent table row, there's no way you also fetch the child entity identifier. The reverse is true. If you fetch the child table row, then you already know the associated parent entity PK.
Quote:
Is there a way to specify a default entity graph for lazy loaded entities and a different entity graph for when the entity is eager fetched? Any other ways to solve this?
Yes, you can. Just follow these steps:
1. You can have the child entity association lazily loaded, which is the best default because
EAGER fetching is bad for performance.
2. When you need to fetch the child entities, you either need to navigate the association as long as the Persistence Context is open, or run a JPQL query if the parent entity is detached:
Code:
select c
from Child c
where c.parent = :parent