Junior — Middle
Where and how should JOIN FETCH be used when calling the findById() method in ORM queries?
sobes.tech AI
Answer from AI
JOIN FETCH is used in ORM (e.g., Hibernate) for eager loading of related entities along with the main entity to avoid the "N+1 query" problem.
When calling the findById() method, if the entity has related collections or objects that need to be fetched immediately, JOIN FETCH should be used in the JPQL or HQL query for these associations.
Example:
@Query("SELECT e FROM Entity e JOIN FETCH e.relatedEntities WHERE e.id = :id")
Entity findByIdWithRelated(@Param("id") Long id);
This way, related data is loaded in a single query, which improves performance and reduces database access.