Sobes.tech
Junior — Middle

Can you give an example of the N+1 problem occurring when using Hibernate?

sobes.tech AI

Answer from AI

The N+1 problem occurs when, during the loading of a collection of related entities, Hibernate executes one query for the main entity (N), and then a separate query for each related entity (+1 for each). For example, consider an entity Author with a collection books:

List<Author> authors = session.createQuery("from Author").list();
for (Author author : authors) {
    System.out.println(author.getBooks().size()); // Lazy loading will trigger a separate query for each book
}

Here, one query is executed initially to fetch all authors, and then a separate query for each author to load their books. This results in many queries and reduces performance.

To avoid this problem, you can use fetch join:

List<Author> authors = session.createQuery("select a from Author a join fetch a.books").list();

This will load authors and their books in a single query.