Menu

Lazy and Eager Fetching, and the N+1 Problem

Lazy and Eager Fetching, and the N+1 Problem

Fetch Types

Eager fetching loads the related data together with the owner. Lazy fetching loads it only when the code first accesses it.

Association

Default

@ManyToOne, @OneToOneEager
@OneToMany, @ManyToManyLazy

Lazy data is loaded through proxies and special collections, so it needs an open session. Accessing it after the session is closed throws LazyInitializationException.

A good habit is to make every association lazy and then load exactly what each use case needs.

The N+1 Problem

The N+1 problem appears when one query loads a list, and then each element triggers its own query to load an association. With 100 employees, this can mean 1 query for the list and many more for departments.

List<Employee> employees = session
        .createQuery("from Employee", Employee.class)
        .getResultList();

for (Employee e : employees) {
    System.out.println(e.getDepartment().getName());
}

List<Employee> fixed = session
        .createQuery("select e from Employee e join fetch e.department", Employee.class)
        .getResultList();

Code Explanation:

  • The first query loads only employees. Each new department reached in the loop triggers another select.
  • join fetch in the second query loads employees and departments in a single SQL join.
  • Other fixes are entity graphs, which choose fetched associations per query, and @BatchSize, which loads related rows in groups.
  • Show the generated SQL with hibernate.show_sql to spot this problem early.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details