Junior — Middle
What data loading mechanism is used when employing JOIN FETCH in ORM?
sobes.tech AI
Answer from AI
JOIN FETCH in ORM (for example, in JPA/Hibernate) is used for eager loading of related entities in a single query.
Mechanism:
- When executing a query with
JOIN FETCH, ORM performs an SQL query with aJOINthat immediately loads the main entity and its related objects. - This prevents the "N+1 query problem," where a separate query is executed for each related entity.
- The loaded related objects are immediately available in memory without additional database access.
Example:
String jpql = "SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id";
Order order = entityManager.createQuery(jpql, Order.class)
.setParameter("id", orderId)
.getSingleResult();
Here, items will be loaded together with Order in a single query.
Thus, JOIN FETCH implements eager loading of related data by joining tables in one query.