Skip to lesson

JPA Entities, Lazy Loading and the N+1 Problem

JPA questions separate people who have only used repositories from people who know what happens underneath. The interviewer wants three explanations in plain words: the persistence context, the N+1 problem, and why a @Transactional method sometimes does not start a transaction.

JPA vs Hibernate vs Spring Data JPA

ORM (object-relational mapping) maps classes to tables and objects to rows, so the framework writes the SQL. JPA is the specification, Hibernate an implementation, and Spring Data JPA the repositories on top.

Three names, three layers. This example maps ShopLite's Product to a table and declares a repository whose implementation Spring generates.

Example 1 · Entities and a Spring Data repository

Runs in: a Spring Boot 4 project with spring-boot-starter-data-jpa and MySQL (Section 16)

SEntityRepo.javaJava
import java.math.BigDecimal;import java.util.List;import java.util.Optional;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.ManyToOne;import jakarta.persistence.Table;import org.springframework.data.jpa.repository.JpaRepository;
@Entity@Table(name = "categories")class Category {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "category_id")    private Long id;
    private String name;
    protected Category() {}                       // JPA needs a no-arg constructor
    public String getName() { return name; }}
@Entity@Table(name = "products")class Product {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "product_id")    private Long id;
    @Column(nullable = false, unique = true, length = 20)    private String sku;
    private String name;    private BigDecimal price;
    @ManyToOne(fetch = FetchType.LAZY)    @JoinColumn(name = "category_id")    private Category category;
    protected Product() {}
    public String getName() { return name; }    public BigDecimal getPrice() { return price; }    public Category getCategory() { return category; }}
// Spring Data JPA writes the implementation at startupinterface ProductRepository extends JpaRepository<Product, Long> {    Optional<Product> findBySku(String sku);                       // derived query    List<Product> findByPriceLessThanOrderByPriceAsc(BigDecimal max);}
public class SEntityRepo {}
Sample output
productRepository.findBySku("MOB-RN13")
Hibernate: select p1_0.product_id,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku from products p1_0 where p1_0.sku=?
-> Optional[Redmi Note 13 5G]

What this code does

  • JPA annotations map the classes to the ShopLite tables; @ManyToOne(fetch = LAZY) links each product to its category without loading it. The protected no-arg constructor is for Hibernate.
  • The repository is only an interface: Spring Data builds findBySku from the method name. With spring.jpa.show-sql=true you see the generated SQL; aliases such as p1_0 vary by Hibernate version.

JPA (Jakarta Persistence) is the specification: @Entity, @Id, @ManyToOne and the EntityManager. Hibernate is the most used implementation and generates the SQL. Spring Data JPA turns ProductRepository extends JpaRepository<Product, Long> into a working class, including derived queries such as findBySku. An entity needs @Entity, an @Id and a no-argument constructor (it may be protected).

Revise: JPA, Hibernate and Spring Data (opens in a new tab), Derived query methods (opens in a new tab).

Order of execution

From repository call to row

Put the layers in the order a call travels through them.

Entity lifecycle and the persistence context

The persistence context is the set of managed entities in one transaction. It returns one object per id (a first-level cache) and does dirty checking: at flush, changed entities are written back as UPDATEs without a save() call.

A managed entity is tracked by the persistence context. This small model behaves like Hibernate: one object per id, and changes are written at commit.

The four states of an entity. A transient object, made with new, has no row and is not tracked. persist() makes it managed, so Hibernate writes its changes at commit. Commit, clear() or detach() make it detached: it still has a row but is no longer tracked.

Example 2 · Persistence context: first-level cache and dirty checking (simplified model)

PersistenceContextSim.javaJava
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.Objects;
public class PersistenceContextSim {    static class Student {        final long id;        String name;
        Student(long id, String name) {            this.id = id;            this.name = name;        }    }
    static Map<Long, String> database = new HashMap<>(Map.of(1L, "Asha", 2L, "Ravi"));
    static class EntityManagerSim {        private final Map<Long, Student> managed = new LinkedHashMap<>();        private final Map<Long, String> snapshot = new HashMap<>();
        Student find(long id) {            Student s = managed.get(id);            if (s != null) {                System.out.println("  find(" + id + "): from persistence context, no SQL");                return s;            }            System.out.println("  SQL: select ... from students where id=" + id);            s = new Student(id, database.get(id));            managed.put(id, s);                       // now MANAGED            snapshot.put(id, s.name);            return s;        }
        void flush() {            for (Student s : managed.values()) {                if (!Objects.equals(snapshot.get(s.id), s.name)) {                    System.out.println("  SQL: update students set name='" + s.name + "' where id=" + s.id);                    database.put(s.id, s.name);                    snapshot.put(s.id, s.name);                }            }        }
        void close() {            managed.clear();                          // entities become DETACHED        }    }
    public static void main(String[] args) {        EntityManagerSim em = new EntityManagerSim();        System.out.println("transaction starts");        Student a = em.find(1);        Student again = em.find(1);        System.out.println("  same object: " + (a == again));        a.name = "Asha Rao";        em.find(2);        System.out.println("commit:");        em.flush();        em.close();        a.name = "changed after close";               // detached: not tracked        System.out.println("database now: " + new java.util.TreeMap<>(database));    }}
Output
transaction starts
  SQL: select ... from students where id=1
  find(1): from persistence context, no SQL
  same object: true
  SQL: select ... from students where id=2
commit:
  SQL: update students set name='Asha Rao' where id=1
database now: {1=Asha Rao, 2=Ravi}

What this code does

  • This small model behaves like Hibernate's persistence context: the second find(1) returns the same object with no SQL, and changing a.name produces an UPDATE at commit without any save() call.
  • After close() the entity is detached, so the last change is never written. Real Hibernate also flushes before queries and batches the SQL.

An entity is transient (new), managed (tracked), detached (context closed) or removed. save calls persist for a new entity or merge for a detached one; saveAndFlush also sends the SQL at once, but neither commits. Flush sends pending SQL inside the transaction; commit makes it permanent.

Revise: Entity lifecycle states (opens in a new tab), Dirty checking (opens in a new tab), Flush and SQL timing (opens in a new tab).

Predict the output

What does Hibernate do?

Every snippet runs inside one @Transactional method unless it says otherwise.

Round 1 of 3

What SQL runs at commit?

Product p = productRepository.findById(1L).orElseThrow();
p.setPrice(new BigDecimal("399"));
// no save() call

Lazy vs eager loading, and LazyInitializationException

Lazy loading fetches a related entity or collection only when you first touch it, through a proxy. It needs an open persistence context; touching it later throws LazyInitializationException. Eager loading fetches it with the parent.

A lazy association is loaded on first use, which needs an open session. This model counts the queries, then touches a lazy field after the session has closed.

Example 3 · N+1 queries and LazyInitializationException (simplified model)

NPlusOneSim.javaJava
import java.util.ArrayList;import java.util.List;
public class NPlusOneSim {    static int queries = 0;
    static class LazyCustomer {        private final long customerId;        private String name;        private final boolean sessionOpen;
        LazyCustomer(long customerId, boolean sessionOpen) {            this.customerId = customerId;            this.sessionOpen = sessionOpen;        }
        String getName() {            if (name == null) {                if (!sessionOpen) {                    throw new IllegalStateException("could not initialize proxy - no Session");                }                queries++;                             // one extra SELECT per order                name = "Customer-" + customerId;            }            return name;        }    }
    record Order(long id, LazyCustomer customer) {}
    static List<Order> findAllOrders(int count, boolean sessionOpen) {        queries++;        List<Order> list = new ArrayList<>();        for (int i = 1; i <= count; i++) {            list.add(new Order(i, new LazyCustomer(100 + i, sessionOpen)));        }        return list;    }
    public static void main(String[] args) {        List<Order> orders = findAllOrders(5, true);        for (Order o : orders) {            o.customer().getName();        }        System.out.println("lazy, 5 orders:  " + queries + " queries (1 + N)");
        queries = 0;        queries++;                                     // select o, c from orders join customers (JOIN FETCH)        System.out.println("join fetch:      " + queries + " query");
        List<Order> detached = findAllOrders(1, false); // transaction already finished        try {            detached.get(0).customer().getName();        } catch (IllegalStateException e) {            System.out.println("outside the transaction: LazyInitializationException: " + e.getMessage());        }    }}
Output
lazy, 5 orders:  6 queries (1 + N)
join fetch:      1 query
outside the transaction: LazyInitializationException: could not initialize proxy - no Session

What this code does

  • Loading 5 orders is 1 query, and touching each lazy customer adds 1 query per order: 6 in total, which is the N+1 problem. A JOIN FETCH loads orders and customers in a single query.
  • Touching a lazy association after the session is closed throws, exactly like Hibernate's LazyInitializationException: could not initialize proxy - no Session.

Defaults: @ManyToOne and @OneToOne are EAGER; @OneToMany and @ManyToMany are LAZY. The best practice is LAZY everywhere and an explicit fetch plan per use case. To fix LazyInitializationException, load what you need inside the transaction (join fetch, entity graph) or map to a DTO in the service. Avoid open-session-in-view, and avoid EAGER everywhere.

Revise: Lazy vs eager fetching (opens in a new tab), LazyInitializationException (opens in a new tab).

Find the bug

Find the cause

One line in each snippet is the problem. Click it.

Jackson fails with LazyInitializationException on order.items. Which line?

Round 1 of 2

The N+1 problem and its fixes

The N+1 problem is one query that loads N parent rows, followed by one extra query per parent when each lazy association is touched: N+1 queries in total. It makes list pages slow as the data grows.

Listing 100 orders with their customers should not take 101 queries. This repository fixes the loop with an entity graph.

The same order list two ways. With N+1, the app sends 1 query for the 16 orders and then 7 more SELECTs, one for each distinct customer: 8 round trips. With a join fetch, one SELECT joins orders and customers: 1 round trip.

Example 4 · Fixing N+1 with JOIN FETCH or @EntityGraph

Runs in: a Spring Boot 4 project with spring-boot-starter-data-jpa and MySQL (Section 16)

SNPlusOneFix.javaJava
import java.util.List;
import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.Id;import jakarta.persistence.ManyToOne;import jakarta.persistence.Table;import org.springframework.data.jpa.repository.EntityGraph;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
@Entityclass Customer {    @Id    private Long id;    private String fullName;
    public String getFullName() { return fullName; }}
@Entity@Table(name = "orders")class PurchaseOrder {    @Id    private Long id;    private String status;
    @ManyToOne(fetch = FetchType.LAZY)    private Customer customer;
    public Long getId() { return id; }    public Customer getCustomer() { return customer; }}
interface OrderRepository extends JpaRepository<PurchaseOrder, Long> {    // Fix 1: JPQL JOIN FETCH loads orders and customers in one query    @Query("select o from PurchaseOrder o join fetch o.customer where o.status = :status")    List<PurchaseOrder> findWithCustomerByStatus(String status);
    // Fix 2: an entity graph on a derived query does the same    @EntityGraph(attributePaths = "customer")    List<PurchaseOrder> findByStatus(String status);}
@Servicepublic class SNPlusOneFix {    private final OrderRepository orders;
    SNPlusOneFix(OrderRepository orders) {        this.orders = orders;    }
    @Transactional(readOnly = true)    public void printPlaced() {        for (PurchaseOrder o : orders.findByStatus("PLACED")) {            System.out.println(o.getId() + " " + o.getCustomer().getFullName());        }    }}
Sample output
Before (plain findByStatus without the entity graph, 3 PLACED orders):
Hibernate: select ... from orders po1_0 where po1_0.status=?
Hibernate: select ... from customer c1_0 where c1_0.id=?
Hibernate: select ... from customer c1_0 where c1_0.id=?
Hibernate: select ... from customer c1_0 where c1_0.id=?

After (@EntityGraph or join fetch):
Hibernate: select ... from orders po1_0 left join customer c1_0 on c1_0.id=po1_0.customer_id where po1_0.status=?
14 Ravi Kumar
15 Asha Rao
16 Meena Iyer

What this code does

  • Without a fetch plan, each getCustomer().getFullName() in the loop fires its own SELECT. @EntityGraph(attributePaths = "customer") (or the join fetch query) loads the customers in the same SQL statement.
  • The service method is @Transactional(readOnly = true), so lazy loading would at least work inside it; the entity graph makes it efficient. Customers are distinct here, so no duplicates appear.

Spot it with SQL logging (spring.jpa.show-sql=true) or by counting queries in a test. Fixes: JOIN FETCH in JPQL, @EntityGraph(attributePaths = ...), batch fetching (@BatchSize, default_batch_fetch_size) or a DTO projection. Trap: join-fetching two collections at once fails with MultipleBagFetchException, and paging with a collection fetch join happens in memory.

Revise: The N+1 problem (opens in a new tab), Fixing N+1 (opens in a new tab).

Predict the output

Count the queries

50 orders from 50 different customers; customer is LAZY.

Round 1 of 3

How many queries run in total?

List<PurchaseOrder> orders = orderRepository.findAll();
for (PurchaseOrder o : orders) {
System.out.println(o.getCustomer().getFullName());
}

@Transactional: rollback rules and the self-invocation trap

Self-invocation is a call from one method of a bean to another method of the same bean. It goes straight to this, not through the Spring proxy, so the second method's @Transactional settings are ignored.

The proxy adds the transaction around calls that come from outside. This model shows why an internal call gets no BEGIN or COMMIT.

Example 5 · Why self-invocation skips @Transactional (a JDK proxy like Spring's)

SelfInvocationDemo.javaJava
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;
// Spring's @Transactional works through a proxy like this oneinterface OrderService {    void placeOrder(String item);    void writeAudit(String item);}
class OrderServiceImpl implements OrderService {    public void placeOrder(String item) {        System.out.println("    placing " + item);        writeAudit(item);                       // this.writeAudit(): does NOT go through the proxy    }
    public void writeAudit(String item) {        System.out.println("    audit for " + item);    }}
public class SelfInvocationDemo {    public static void main(String[] args) {        OrderService target = new OrderServiceImpl();        InvocationHandler tx = (proxy, method, a) -> {            System.out.println("  BEGIN transaction for " + method.getName());            Object result = method.invoke(target, a);            System.out.println("  COMMIT transaction for " + method.getName());            return result;        };        OrderService proxy = (OrderService) Proxy.newProxyInstance(                OrderService.class.getClassLoader(), new Class<?>[] {OrderService.class}, tx);
        System.out.println("call through the proxy:");        proxy.placeOrder("headphones");        System.out.println("direct external call to writeAudit:");        proxy.writeAudit("charger");    }}
Output
call through the proxy:
  BEGIN transaction for placeOrder
    placing headphones
    audit for headphones
  COMMIT transaction for placeOrder
direct external call to writeAudit:
  BEGIN transaction for writeAudit
    audit for charger
  COMMIT transaction for writeAudit

What this code does

  • Calls through the proxy get BEGIN and COMMIT. Inside placeOrder, the call writeAudit(item) is this.writeAudit(...) on the real object, so the proxy never sees it: if writeAudit had REQUIRES_NEW, it would be ignored.
  • An external caller reaching writeAudit through the proxy does get its own transaction. Spring Boot usually uses class-based (CGLIB) proxies, but the rule is the same.

@Transactional rolls back only on RuntimeException and Error; checked exceptions commit unless you set rollbackFor. REQUIRED (the default) joins an existing transaction; REQUIRES_NEW suspends it and starts another, for example for an audit log. readOnly = true lets Hibernate skip dirty checking. Fix self-invocation by moving the method to another bean; private methods are never intercepted.

Revise: Rollback rules (opens in a new tab), Propagation (opens in a new tab), Transactional pitfalls (opens in a new tab).

Find the bug

Why is the transaction ignored?

One line in each snippet is the problem. Click it.

importMarks should undo the save when the file is corrupt, but the mark stays. Which line?

Round 1 of 3

Next step

Check your understanding

12 quick questions