Back to Lazy & Eager Fetching
Q1Question 1 of 1

What is LazyInitializationException and how do you fix it

Answer: LazyInitializationException is a Hibernate runtime error thrown when you access a lazily loaded collection or entity proxy after the persistence context (Hibernate session) has been closed.

Key Concepts
  • LazyInitializationException occurs when you access a lazily loaded collection or proxy after the Hibernate session has closed.
  • FetchType.LAZY is the default for @OneToMany and @ManyToMany, meaning collections are not loaded until accessed.
  • JOIN FETCH in JPQL loads the parent entity and its collection in a single SQL query, preventing the exception.
  • @EntityGraph is a declarative alternative to JOIN FETCH that you place on a Spring Data repository method.
  • DTO projection avoids the problem entirely by selecting only needed fields into a plain Java object with no proxy.
  • Open Session in View (OSIV) masks the exception but causes database connection pool exhaustion under load.
  • The correct approach is to keep FetchType.LAZY as the default and choose the right fetch strategy per use case.

Definition

LazyInitializationException is a Hibernate runtime error thrown when you access a lazily loaded collection or entity proxy after the persistence context (Hibernate session) has been closed.
  • LazyInitializationException is thrown by Hibernate when code accesses an uninitialized proxy or collection outside an active session.
  • Lazy loading means Hibernate creates a proxy placeholder for a collection and loads the real data only when your code first accesses it.
  • Persistence context (Hibernate session) is the bridge between Java objects and the database; it opens with a transaction and closes when the transaction ends.
  • Fetch join is a JPQL clause that loads a parent entity and its association in a single SQL query, ensuring the collection is initialized before the session closes.
  • @EntityGraph is a Spring Data JPA annotation that declaratively specifies which associations to load eagerly for a specific repository method.
  • DTO projection selects only the needed columns into a plain Java object, avoiding entity proxies entirely.

Think of a bank filing room. When a clerk (Hibernate session) is on duty, you can ask for any file and the clerk fetches it from the cabinet. Lazy loading means the clerk writes a note saying "Transaction records for SAV2001 are in Cabinet 7" instead of fetching them immediately. As long as the clerk is on duty, you can hand back the note and get the real files. But when the clerk leaves for the day (session closes) and you try to use that note, nobody is there to fetch the files. That is LazyInitializationException: the note (proxy) exists, but the clerk (session) is gone.

Understanding the Concepts

What is LazyInitializationException?

LazyInitializationException is a runtime exception from the org.hibernate package. Hibernate throws it when your code tries to access a lazily loaded collection or an uninitialized entity proxy after the persistence context has been closed.

The full exception message looks like this:

TEXT
org.hibernate.LazyInitializationException:
  failed to lazily initialize a collection of role:
  com.bank.model.Account.transactions:
  could not initialize proxy - no Session

This means Hibernate tried to execute a SQL query to load the transactions collection, but no database session was available to run the query.

Why does JPA use lazy loading by default for collections?

JPA uses FetchType.LAZY as the default for @OneToMany and @ManyToMany associations because loading related collections eagerly causes severe performance problems.

Consider account SAV2001 at National Bank of India. This savings account might have 50,000 transactions over its lifetime. If JPA loaded all 50,000 transactions every time you queried the account (even just to check the balance), the application would be unusably slow.

Lazy loading means the collection is not loaded from the database until your code accesses it. Hibernate creates a proxy object that stands in for the real collection. When you call account.getTransactions() while the session is still open, Hibernate fires a SQL query at that moment to load the data.

  • FetchType.LAZY is the default for @OneToMany and @ManyToMany.
  • FetchType.EAGER is the default for @ManyToOne and @OneToOne.
  • Lazy loading prevents loading unnecessary data, improving performance.
  • The trade-off is that accessing the collection outside a session causes LazyInitializationException.
JAVA
package com.bank.model;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "accounts")
public class Account {

    @Id
    @Column(name = "account_id")
    private String accountId;

    @Column(name = "holder_name", nullable = false)
    private String holderName;

    @Column(nullable = false, precision = 15, scale = 2)
    private BigDecimal balance;

    // LAZY is the default for @OneToMany, shown explicitly for clarity
    @OneToMany(mappedBy = "account", fetch = FetchType.LAZY)
    private List<Transaction> transactions = new ArrayList<>();

    public String getAccountId() { return accountId; }
    public String getHolderName() { return holderName; }
    public BigDecimal getBalance() { return balance; }
    public List<Transaction> getTransactions() { return transactions; }
}
JAVA
package com.bank.model;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Entity
@Table(name = "transactions")
public class Transaction {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "txn_id")
    private Long txnId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "account_id", nullable = false)
    private Account account;

    @Column(name = "txn_type", nullable = false)
    private String txnType;

    @Column(nullable = false, precision = 15, scale = 2)
    private BigDecimal amount;

    private String description;

    @Column(name = "created_at", nullable = false)
    private LocalDateTime createdAt;

    public Long getTxnId() { return txnId; }
    public String getTxnType() { return txnType; }
    public BigDecimal getAmount() { return amount; }
    public String getDescription() { return description; }
    public LocalDateTime getCreatedAt() { return createdAt; }
}

How does the Hibernate session lifecycle cause this exception?

The Hibernate session (persistence context) is created when a transaction begins and destroyed when the transaction commits or rolls back. In Spring Boot, the @Transactional annotation controls this lifecycle.

Here is the exact sequence that causes LazyInitializationException:

  1. A controller calls a @Transactional service method.
  2. Spring creates a Hibernate session and begins a transaction.
  3. The service loads Account SAV2001. The transactions collection is a proxy (not loaded).
  4. The service returns the Account object. The @Transactional method ends.
  5. Spring commits the transaction and closes the Hibernate session.
  6. The controller calls account.getTransactions(). The proxy tries to load data, but there is no session.
  7. Hibernate throws LazyInitializationException.
JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    private final AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional(readOnly = true)
    public Account findAccount(String accountId) {
        // Session is OPEN here. Account loaded, transactions = proxy.
        return accountRepository.findById(accountId)
            .orElseThrow(() -> new RuntimeException(
                "Account not found: " + accountId));
    }
    // Session CLOSES when this method returns.
}
JAVA
package com.bank.controller;

import com.bank.model.Account;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    private final AccountService accountService;

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/{id}/transactions")
    public String getTransactions(@PathVariable("id") String accountId) {
        Account account = accountService.findAccount(accountId);

        // Session is CLOSED here. This line throws LazyInitializationException.
        int count = account.getTransactions().size();

        return "Account " + accountId + " has " + count + " transactions";
    }
}
TEXT
GET /api/accounts/SAV2001/transactions

HTTP 500 Internal Server Error
org.hibernate.LazyInitializationException:
  failed to lazily initialize a collection of role:
  com.bank.model.Account.transactions:
  could not initialize proxy - no Session

How do you fix it with JOIN FETCH in JPQL?

JOIN FETCH tells Hibernate to load the Account and its transactions in a single SQL query. The collection is fully initialized before the session closes, so there is no proxy to trigger later.

This is the most explicit and widely used fix.

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;

public interface AccountRepository extends JpaRepository<Account, String> {

    @Query("SELECT a FROM Account a JOIN FETCH a.transactions WHERE a.accountId = :id")
    Optional<Account> findByIdWithTransactions(@Param("id") String accountId);
}
JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    private final AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional(readOnly = true)
    public Account findAccountWithTransactions(String accountId) {
        return accountRepository.findByIdWithTransactions(accountId)
            .orElseThrow(() -> new RuntimeException(
                "Account not found: " + accountId));
    }
}
TEXT
Hibernate SQL log:
  select a1_0.account_id, a1_0.balance, a1_0.holder_name,
         t1_0.txn_id, t1_0.amount, t1_0.created_at,
         t1_0.description, t1_0.txn_type
    from accounts a1_0
    join transactions t1_0 on a1_0.account_id = t1_0.account_id
   where a1_0.account_id = 'SAV2001'

Result: 1 SQL query loads both Account and all Transactions.
No LazyInitializationException.

How do you fix it with @EntityGraph?

@EntityGraph is a declarative way to specify which associations to load eagerly for a specific query. It achieves the same result as JOIN FETCH but without writing JPQL.

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface AccountRepository extends JpaRepository<Account, String> {

    @EntityGraph(attributePaths = "transactions")
    Optional<Account> findByAccountId(String accountId);
}
TEXT
Hibernate SQL log:
  select a1_0.account_id, a1_0.balance, a1_0.holder_name,
         t1_0.txn_id, t1_0.amount, t1_0.created_at,
         t1_0.description, t1_0.txn_type
    from accounts a1_0
    left join transactions t1_0 on a1_0.account_id = t1_0.account_id
   where a1_0.account_id = ?

Note: @EntityGraph uses LEFT JOIN by default, so accounts
with zero transactions are still returned.

You can also define a named entity graph on the entity class:

JAVA
@Entity
@Table(name = "accounts")
@NamedEntityGraph(
    name = "Account.withTransactions",
    attributeNodes = @NamedAttributeNode("transactions")
)
public class Account {
    // fields and mappings as shown above
}
JAVA
// Usage in repository
@EntityGraph("Account.withTransactions")
Optional<Account> findByAccountId(String accountId);

For nested associations (transactions that reference a branch), use subgraphs:

JAVA
@NamedEntityGraph(
    name = "Account.full",
    attributeNodes = {
        @NamedAttributeNode(value = "transactions", subgraph = "txn-details")
    },
    subgraphs = {
        @NamedSubgraph(name = "txn-details",
            attributeNodes = @NamedAttributeNode("branch"))
    }
)

How do you fix it with DTO projection?

DTO projection avoids lazy loading entirely by selecting only the fields you need into a plain Java object. There is no entity, no proxy, and no risk of LazyInitializationException.

This is the best approach when you need read-only data for an API response.

JAVA
package com.bank.dto;

import java.math.BigDecimal;

public record AccountSummaryDTO(
    String accountId,
    String holderName,
    BigDecimal balance,
    long transactionCount
) {}
JAVA
package com.bank.repository;

import com.bank.dto.AccountSummaryDTO;
import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;

public interface AccountRepository extends JpaRepository<Account, String> {

    @Query("""
        SELECT new com.bank.dto.AccountSummaryDTO(
            a.accountId, a.holderName, a.balance,
            (SELECT COUNT(t) FROM Transaction t WHERE t.account = a)
        )
        FROM Account a
        WHERE a.accountId = :id
        """)
    Optional<AccountSummaryDTO> findAccountSummary(@Param("id") String accountId);
}
JAVA
package com.bank.controller;

import com.bank.dto.AccountSummaryDTO;
import com.bank.repository.AccountRepository;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    private final AccountRepository accountRepository;

    public AccountController(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @GetMapping("/{id}/summary")
    public AccountSummaryDTO getAccountSummary(
            @PathVariable("id") String accountId) {
        return accountRepository.findAccountSummary(accountId)
            .orElseThrow(() -> new RuntimeException(
                "Account not found: " + accountId));
    }
}
TEXT
GET /api/accounts/SAV2001/summary

{
  "accountId": "SAV2001",
  "holderName": "Rajesh Kumar",
  "balance": 75000.00,
  "transactionCount": 142
}

Hibernate SQL:
  select a1_0.account_id, a1_0.holder_name, a1_0.balance,
         (select count(*) from transactions t1_0
          where t1_0.account_id = a1_0.account_id)
    from accounts a1_0
   where a1_0.account_id = 'SAV2001'

No entity loaded. No proxy. No LazyInitializationException possible.

How is FetchType.LAZY different from FetchType.EAGER?

FeatureFetchType.LAZYFetchType.EAGER
When data loadsOn first access of the collectionImmediately with the parent query
Default for@OneToMany, @ManyToMany@ManyToOne, @OneToOne
SQL queriesSeparate query when collection accessedJOIN or subselect with parent query
RiskLazyInitializationException if session closedN+1 problem and unnecessary data loading
PerformanceGood when collection is not always neededBad for large collections
ControlDeveloper chooses when and how to loadAlways loads, no way to skip
JAVA
// LAZY: Transactions are NOT loaded with this query
@OneToMany(mappedBy = "account", fetch = FetchType.LAZY)
private List<Transaction> transactions;

// Hibernate executes 1 query:
//   SELECT * FROM accounts WHERE account_id = 'SAV2001'
// Transactions NOT loaded yet.
JAVA
// EAGER: Transactions are ALWAYS loaded with this query
@OneToMany(mappedBy = "account", fetch = FetchType.EAGER)
private List<Transaction> transactions;

// Hibernate executes 2 queries:
//   SELECT * FROM accounts WHERE account_id = 'SAV2001'
//   SELECT * FROM transactions WHERE account_id = 'SAV2001'
// Both load even if you only need the balance.
TEXT
LAZY scenario (finding 10 accounts to display balances):
  SQL: SELECT * FROM accounts WHERE branch_id = 101
  Result: 1 query. Transactions not loaded. Fast.

EAGER scenario (same query, 10 accounts):
  SQL: SELECT * FROM accounts WHERE branch_id = 101
  SQL: SELECT * FROM transactions WHERE account_id = 'SAV2001'
  SQL: SELECT * FROM transactions WHERE account_id = 'SAV2002'
  ... (8 more queries)
  Result: 11 queries total. This is the N+1 problem.

What are common mistakes?

Mistake 1: Enabling Open Session in View (OSIV)

WRONG: OSIV keeps the Hibernate session open for the entire HTTP request, including the controller and view layer. This masks LazyInitializationException but introduces database connection leaks.

TEXT
# WRONG: application.properties
spring.jpa.open-in-view=true

The database connection stays open while the JSON response is being
serialized. If serialization takes 2 seconds (large payload, slow
client), the connection is held idle for 2 seconds. Under 200
concurrent requests, the connection pool (default 10) is exhausted
and the application stops responding.

CORRECT: Disable OSIV and use explicit fetch strategies.

TEXT
# CORRECT: application.properties
spring.jpa.open-in-view=false

Spring Boot logs this warning when OSIV is enabled:
"spring.jpa.open-in-view is enabled by default. Therefore, database
queries may be performed during view rendering. Explicitly configure
spring.jpa.open-in-view to disable this warning."

Mistake 2: Switching every association to FetchType.EAGER

WRONG: Changing the mapping to EAGER loads the collection on every query, even when you do not need it.

JAVA
// WRONG: Every query for Account now loads all transactions
@OneToMany(mappedBy = "account", fetch = FetchType.EAGER)
private List<Transaction> transactions;

// Even this simple balance check loads 50,000 transactions:
Account account = accountRepository.findById("SAV2001").get();
BigDecimal balance = account.getBalance();
// transactions loaded but never used. Wasted memory and queries.

CORRECT: Keep LAZY and use a fetch join or entity graph only for the queries that need the collection.

JAVA
// CORRECT: Keep LAZY on the entity
@OneToMany(mappedBy = "account", fetch = FetchType.LAZY)
private List<Transaction> transactions;

// Load transactions explicitly only when needed:
Account withTxns = accountRepository.findByIdWithTransactions("SAV2001");
int count = withTxns.getTransactions().size(); // works, loaded by JOIN FETCH

// For queries that don't need transactions, use the normal findById:
Account account = accountRepository.findById("SAV2001").get();
BigDecimal balance = account.getBalance(); // fast, transactions NOT loaded

Mistake 3: Calling Hibernate.initialize() in the controller

WRONG: Forcing initialization in the controller layer ties your controller to Hibernate internals.

JAVA
// WRONG: Controller depends on Hibernate API
@GetMapping("/{id}/transactions")
public List<Transaction> getTransactions(@PathVariable String id) {
    Account account = accountService.findAccount(id);
    Hibernate.initialize(account.getTransactions()); // bad practice
    return account.getTransactions();
}

CORRECT: The service layer should return fully initialized data.

JAVA
// CORRECT: Service returns what the controller needs
@Transactional(readOnly = true)
public Account findAccountWithTransactions(String accountId) {
    return accountRepository.findByIdWithTransactions(accountId)
        .orElseThrow();
}

What about @BatchSize and subselect fetching?

When you load multiple accounts and need their transactions, Hibernate can batch the lazy loading queries instead of firing one query per account.

@BatchSize(size = 20) tells Hibernate to load transactions for up to 20 accounts in a single SQL query using an IN clause.

JAVA
@Entity
@Table(name = "accounts")
public class Account {

    @OneToMany(mappedBy = "account", fetch = FetchType.LAZY)
    @BatchSize(size = 20)
    private List<Transaction> transactions = new ArrayList<>();
}
TEXT
Without @BatchSize (N+1 problem, loading 10 accounts):
  SELECT * FROM accounts WHERE branch_id = 101             -- 1 query
  SELECT * FROM transactions WHERE account_id = 'SAV2001'  -- +1
  SELECT * FROM transactions WHERE account_id = 'SAV2002'  -- +1
  ... (8 more queries)
  Total: 11 queries

With @BatchSize(size = 20):
  SELECT * FROM accounts WHERE branch_id = 101             -- 1 query
  SELECT * FROM transactions WHERE account_id IN (
    'SAV2001','SAV2002','SAV2003','SAV2004','SAV2005',
    'SAV2006','SAV2007','SAV2008','SAV2009','SAV2010'
  )                                                         -- 1 query
  Total: 2 queries

You can also set a global default batch size in application.properties:

TEXT
# application.properties
spring.jpa.properties.hibernate.default_batch_fetch_size=20

What about pagination with fetch join?

When you combine JOIN FETCH with pagination (Pageable in Spring Data), Hibernate cannot apply LIMIT/OFFSET at the SQL level because the join produces multiple rows per parent entity. Hibernate loads all results into memory and paginates there, logging a warning.

TEXT
HHH90003004: firstResult/maxResults specified with collection fetch;
applying in memory

This is dangerous for large data sets. If you have 100,000 accounts, Hibernate loads all of them into memory before applying the page limit.

The fix is to use a two-query approach:

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

public interface AccountRepository extends JpaRepository<Account, String> {

    // Query 1: Get paginated account IDs
    @Query("SELECT a.accountId FROM Account a WHERE a.holderName LIKE :name")
    Page<String> findAccountIds(String name, Pageable pageable);

    // Query 2: Fetch accounts with transactions for the selected IDs
    @Query("SELECT a FROM Account a JOIN FETCH a.transactions WHERE a.accountId IN :ids")
    List<Account> findByIdsWithTransactions(List<String> ids);
}
JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class AccountService {

    private final AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional(readOnly = true)
    public List<Account> findAccountsWithTransactions(
            String namePattern, Pageable pageable) {

        // Query 1: Paginated IDs (fast, no join)
        Page<String> idPage = accountRepository
            .findAccountIds(namePattern, pageable);

        // Query 2: Fetch full entities for the page of IDs
        return accountRepository
            .findByIdsWithTransactions(idPage.getContent());
    }
}
TEXT
Query 1: SELECT a.account_id FROM accounts a
         WHERE a.holder_name LIKE '%Kumar%'
         LIMIT 10 OFFSET 0

Query 2: SELECT a.*, t.*
         FROM accounts a
         JOIN transactions t ON a.account_id = t.account_id
         WHERE a.account_id IN ('SAV2001','SAV2002',...)

Result: 2 queries, proper pagination, no in-memory warning.

What should a senior or principal engineer know?

- Hibernate proxy mechanism. Hibernate uses ByteBuddy (previously Javassist) to generate a subclass of your entity at runtime. This subclass overrides getter methods to intercept the first access and load data from the database. The proxy is why your entity class must not be final and must have a no-arg constructor.

- MultipleBagFetchException. If you try to JOIN FETCH two List collections in the same query (for example, account.transactions and account.beneficiaries), Hibernate throws MultipleBagFetchException. The fix is to change one of the lists to a Set, or use two separate queries.

JAVA
// WRONG: Two List fetch joins cause MultipleBagFetchException
@Query("SELECT a FROM Account a JOIN FETCH a.transactions JOIN FETCH a.beneficiaries")
List<Account> findAll();

// FIX: Change one collection to Set
@OneToMany(mappedBy = "account")
private Set<Beneficiary> beneficiaries = new HashSet<>();

- Second-level cache interaction. When Hibernate's second-level cache is enabled, a cached entity may have uninitialized proxies. Accessing a lazy collection on a cached entity still requires a session. Use cache regions that store fully initialized DTOs instead of entities for read-heavy queries.

- Hibernate 6 fetch profiles. Hibernate 6 (used in Spring Boot 3.x) supports @FetchProfile annotations that let you define named fetch strategies and activate them programmatically in a session, providing more flexibility than @EntityGraph.

- Jackson serialization and infinite loops. When Jackson serializes an Account entity with a bidirectional @OneToMany/@ManyToOne relationship, it can enter an infinite loop. Use @JsonManagedReference and @JsonBackReference, or use DTO projection to avoid exposing entities in API responses.

What are common interview follow-up questions?

  • What is the difference between JOIN FETCH and a regular JOIN in JPQL?
  • How do you solve the N+1 select problem?
  • Can you use @EntityGraph with Spring Data JPA derived query methods?
  • What is the difference between FetchType.LAZY and FetchType.EAGER?
  • Why should you disable Open Session in View in production?
  • How do you paginate results when using JOIN FETCH?
  • What is MultipleBagFetchException and how do you fix it?
  • When should you use DTO projection instead of entity fetching?

Visual Overview

DIAGRAM
  Session Lifecycle and LazyInitializationException
  ===================================================

  @Transactional method (service layer)
  ┌────────────────────────────────────────────┐
  │  Session OPEN                              │
  │                                            │
  │  1. findById("SAV2001")             [OK]   │
  │  2. Account loaded from database           │
  │  3. transactions = PROXY (not loaded)      │
  │                                            │
  └────────────────────────────────────────────┘
           │
           │  Method returns, @Transactional ends
           │  Session CLOSES
           ▼
  Controller layer (no session)
  ┌────────────────────────────────────────────┐
  │  Session CLOSED                            │
  │                                            │
  │  4. account.getTransactions()              │
  │     Proxy tries to load from database      │
  │     No session available                   │
  │     LazyInitializationException!           │
  └────────────────────────────────────────────┘
DIAGRAM
  Three Fixes Compared
  =====================

  Fix 1: JOIN FETCH (JPQL)
  ┌──────────────────────────────────────────┐
  │  SELECT a FROM Account a                 │
  │    JOIN FETCH a.transactions              │
  │  WHERE a.accountId = :id                 │
  │                                          │
  │  1 SQL query, entities fully loaded      │
  │  Best for: service methods needing       │
  │  the full entity graph                   │
  └──────────────────────────────────────────┘

  Fix 2: @EntityGraph (annotation)
  ┌──────────────────────────────────────────┐
  │  @EntityGraph(attributePaths =            │
  │    "transactions")                        │
  │  Optional<Account> findByAccountId(id)   │
  │                                          │
  │  Same SQL as JOIN FETCH, no JPQL needed  │
  │  Best for: Spring Data repository methods│
  └──────────────────────────────────────────┘

  Fix 3: DTO Projection
  ┌──────────────────────────────────────────┐
  │  SELECT new AccountSummaryDTO(           │
  │    a.accountId, a.holderName, ...)       │
  │                                          │
  │  No entity, no proxy, no lazy loading    │
  │  Best for: read-only API responses       │
  └──────────────────────────────────────────┘

Key Takeaway

LazyInitializationException is one of the most common errors in JPA and Hibernate applications. It happens when code tries to access a lazily loaded collection or proxy after the Hibernate session has closed. In a banking application at National Bank of India, this occurs when a controller tries to read the transactions of Account SAV2001 that was loaded inside a @Transactional service method.

The root cause is the mismatch between the entity lifecycle and the business logic that uses it. The session opens when the transaction begins and closes when the transaction commits. If your code accesses a lazy collection after the commit, there is no session to execute the database query. Hibernate has no choice but to throw the exception.

Three solutions exist, and each is appropriate for different situations. JOIN FETCH loads the entity and its collection in a single SQL query, making it the best choice when you always need the related data. @EntityGraph achieves the same result declaratively on a Spring Data repository method. DTO projection avoids the problem entirely by selecting only the fields you need into a plain Java record, with no entity and no proxy.

The wrong approaches are enabling Open Session in View (OSIV) or switching every mapping to FetchType.EAGER. OSIV keeps a database connection open for the entire HTTP request, leading to connection pool exhaustion under load. Eager fetching loads collections unconditionally, turning simple queries into N+1 performance disasters where loading 10 accounts fires 11 SQL queries.

Remember one sentence: keep FetchType.LAZY as the default, disable OSIV, and choose the right fetch strategy for each use case.

---

Share