Hibernate / MyBatis Interview questions
What is the N+1 select problem, and how does it relate to MyBatis?
The N+1 select problem occurs when fetching a list of N parent records triggers one additional query per parent to fetch each one's related data, resulting in 1 (for the parent list) plus N (one per parent's related data) separate queries, instead of a single, more efficient query that retrieves everything together.
In MyBatis specifically, this pattern commonly arises from using the nested select strategy for associations or collections — where a related object or list is fetched via a separate statement referenced through the select attribute — rather than the nested result (join-based) strategy that retrieves everything in one query.
Mitigating it generally means one of a few approaches: switching to a nested result (join-based) mapping so the database does the work in one query; enabling and tuning lazy loading so the extra queries only fire when actually needed rather than eagerly for every parent row regardless of use; or, for cases where nested select is still preferred, using MyBatis's batch-fetching optimizations for nested selects, which can consolidate what would otherwise be N separate queries into a smaller number of batched lookups — the right fix depends on whether the related data is needed for every parent row in practice, or only occasionally.
More Related questions...