When you need to fetch a root entity along with an optionally associated entity through an intermediate join table, standard LEFT JOIN FETCH won't work if the intermediate entity is optional. The solution uses a JPQL query with a Record-based projection (Java Record) that wraps both the root entity and the optional entity. The fetched entities remain managed by the Persistence Context, so dirty checking and automatic flushing still work. This approach avoids fetching the intermediate entity while keeping the result entities fully managed.

5m read timeFrom vladmihalcea.com
Post cover image
Table of contents
IntroductionDomain ModelThe ProblemThe SolutionConclusion

Sort: