Lazy vs Eager Fetching and LazyInitializationException

Difficulty: Intermediate

Question

What is the difference between lazy and eager fetching in JPA, and why do you sometimes get LazyInitializationException?

Answer

Fetch type answers one question: when a parent entity is loaded, should its related data come along immediately or only when someone actually touches it? Eager means immediately, lazy means on demand. The choice affects performance and, as you may have hit already, can throw one of the most confusing exceptions in Spring development.

The JPA defaults are worth memorising because interviewers ask. @OneToMany and @ManyToMany are lazy by default. @ManyToOne and @OneToOne are eager by default. Eager loading fetches the association together with the owner, through a join or an additional select, whether you need it or not. Lazy loading instead places a proxy object or a special collection, like Hibernate's PersistentBag, in the field. The real data is loaded from the database the first time you access it, provided the persistence session is still open.

Now the exception. LazyInitializationException: could not initialize proxy, no Session. This happens when you touch a lazy association after the Hibernate session has closed. A typical chain: the controller calls a service, the service has @Transactional and loads a Student, the transaction ends when the method returns, and later the controller or Jackson calls student.getCourses(). The proxy tries to hit the database, but the session is gone, so it throws. Imagine a library card that expires when you leave the building, and you try to borrow a book from home.

Ways to fix it properly. One: load what you need inside the transaction, using a join fetch, an @EntityGraph, or by touching the collection inside the service method. Two: map to a DTO inside the transactional service and return only the DTO, so no entity crosses the boundary. This is the recommended approach because it also protects your API contract. Three: use a projection query. What you should not do is set spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true, which opens a new connection per lazy access and silently creates N+1 queries and connection pressure. That property exists, but treat it as an anti-pattern.

Open Session In View is the related Spring Boot default that catches people out. spring.jpa.open-in-view is true by default, which keeps the EntityManager open for the entire web request, including view rendering and JSON serialisation. That is why lazy loading appears to work in controllers in many projects, but it keeps database connections held longer, hides performance problems, and moves queries outside the transactional boundary. Many teams set it to false so problems show up in development rather than production, and Boot itself logs a warning about it at startup.

Best practice summary: keep associations lazy, including ManyToOne, by writing fetch = FetchType.LAZY explicitly. Decide per use case what to load using fetch joins or entity graphs. Return DTOs, not entities, and disable open-in-view for predictable behaviour.

Code examples

Reproducing and fixing LazyInitializationException

@Service
@RequiredArgsConstructor
class StudentService {
    private final StudentRepository repo;

    // BUG: entity leaves the transaction with an uninitialised collection
    @Transactional(readOnly = true)
    public Student findEntity(Long id) {
        return repo.findById(id).orElseThrow();
    }

    // FIX 1: map to DTO inside the transaction
    @Transactional(readOnly = true)
    public StudentDto findDto(Long id) {
        Student s = repo.findById(id).orElseThrow();
        return new StudentDto(s.getId(), s.getName(),
                s.getCourses().stream().map(Course::getTitle).toList());
    }
}

interface StudentRepository extends JpaRepository<Student, Long> {
    // FIX 2: load the association explicitly
    @EntityGraph(attributePaths = "courses")
    Optional<Student> findWithCoursesById(Long id);
}

// application.yml
// spring.jpa.open-in-view: false

Either shape the data inside the transaction or fetch the association explicitly, and turn off open-in-view to surface mistakes early.

Key points

Common follow-up questions

Interview tips

Concepts covered

Lazy Loading, Eager Loading, LazyInitializationException, Open Session In View

More Spring Boot questions