Middle
Will the JOIN FETCH operation be performed when using lazy loading?
sobes.tech AI
Answer from AI
The JOIN FETCH operation in JPA is used for eager loading of associated entities, meaning it loads related objects immediately along with the main query. The lazy loading annotation or setting (FetchType.LAZY) indicates that related data should only be loaded on demand.
If the query uses JOIN FETCH, then related entities will be loaded immediately, regardless of what is specified in the lazy loading annotation. That is, JOIN FETCH overrides the loading strategy and forces eager loading.
Thus, when using JOIN FETCH, the operation will be executed and related data will be loaded immediately, despite the lazy loading set in the mapping.
Example:
String jpql = "SELECT p FROM Parent p JOIN FETCH p.children WHERE p.id = :id";
Parent parent = entityManager.createQuery(jpql, Parent.class)
.setParameter("id", 1L)
.getSingleResult();
// Children will be loaded immediately, even if Parent.children has FetchType.LAZY