Hibernate / EclipseLink Interview questions
How do you configure batch fetching using EclipseLink query hints?
Batch fetching solves the classic N+1 query problem: instead of issuing a separate SQL query for each entity's related collection or reference as it's lazily accessed, EclipseLink issues one additional query that fetches the related data for every entity in the original result set at once.
TypedQuery<Employee> query = em.createQuery( "SELECT e FROM Employee e WHERE e.department = :dept", Employee.class); query.setParameter("dept", department); query.setHint("eclipselink.batch", "e.projects"); query.setHint("eclipselink.batch.type", "IN"); List<Employee> employees = query.getResultList(); // Accessing employee.getProjects() for any employee in the list // triggers one batched query for all of them, not one query each.
The eclipselink.batch.type hint controls the SQL strategy used for the batch query itself: IN uses an IN clause with the parent IDs, JOIN uses an outer join in the original query, and EXISTS uses a correlated subquery, each with different tradeoffs depending on the size of the result set and the database's query optimizer.
More Related questions...