# N+1 and its fixes: statements sent for 5 departments with 3 employees each # Hibernate ORM 7.4.16.Final, H2, JDK 25 -- naive: query departments, then touch each employees collection sql> select d1_0.id,d1_0.name from departments d1_0 sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? departments returned: 5 (no DISTINCT needed in Hibernate 7) -- fix 1: left join fetch d.employees sql> select d1_0.id,e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid,d1_0.name from departments d1_0 left join employees e1_0 on d1_0.id=e1_0.dept_id -- fix 2: @BatchSize(size = 20) on the collection, same loop as the naive one sql> select bd1_0.id from BatchDept bd1_0 sql> select e1_0.dept_id,e1_0.id,e1_0.name from BatchEmp e1_0 where e1_0.dept_id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)