Sobes.tech
Junior — Middle

Have you experienced the N+1 problem when using Hibernate?

sobes.tech AI

Answer from AI

The N+1 problem in Hibernate occurs when, during the retrieval of a collection of entities, a separate database query is executed for each entity, leading to an excessive number of queries.

For example, if you have a list of users and want to get a list of orders for each, with incorrect Hibernate configuration, it first executes one query to get the users (1), and then a separate query for each user's orders (N), totaling N+1 queries.

To avoid this problem, the following are used:

  • Eager fetching: using JOIN FETCH in HQL or the @Fetch(FetchMode.JOIN) annotation.
  • Entity Graphs: to specify which associations to load immediately.
  • Batch fetching: configuring Hibernate to load related entities in batches.

Example with JOIN FETCH:

String hql = "FROM User u JOIN FETCH u.orders WHERE u.id = :userId";
List<User> users = session.createQuery(hql, User.class).getResultList();

This allows loading users and their orders with a single query, avoiding N+1.