Junior — Middle
Explain the N+1 problem that can occur when using Hibernate, and how to avoid it.
sobes.tech AI
Answer from AI
The N+1 problem in Hibernate occurs when, during the loading of a collection of related entities, one query is executed for the main entity (1), and then a separate query for each of the N related entities. This leads to a large number of database queries and reduced performance.
For example, when loading a list of users and their roles, if roles are loaded lazily, Hibernate will execute 1 query for users and N queries for each user's roles.
To avoid the N+1 problem, the following are used:
- Eager fetching with
JOIN FETCHin HQL or the@Fetch(FetchMode.JOIN)annotation. - Entity Graphs to specify which associations to load immediately.
- Batch fetching — loading related entities in batches.
Example with JOIN FETCH:
String hql = "FROM User u JOIN FETCH u.roles";
List<User> users = session.createQuery(hql, User.class).list();
This allows loading users and their roles with a single query, eliminating the N+1 problem.