0
0
Spring Bootframework~3 mins

Fetch types (LAZY vs EAGER) in Spring Boot - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how smart data loading can make your app lightning fast and efficient!

The Scenario

Imagine you have a list of books, and each book has many authors. You want to show just the book titles on a page. If you manually load all authors for every book upfront, it feels like carrying a heavy backpack full of unnecessary stuff.

The Problem

Loading all related data at once makes your app slow and uses too much memory. If you only need some data, fetching everything wastes time and resources. Manually controlling this is tricky and error-prone.

The Solution

Fetch types like LAZY and EAGER let Spring Boot decide when to load related data. LAZY loads data only when needed, like unpacking your backpack only when you want something. EAGER loads everything immediately, useful when you know you need all data.

Before vs After
Before
List<Book> books = bookRepository.findAll(); // manually fetch authors for each book later
After
@OneToMany(fetch = FetchType.LAZY)
List<Author> authors; // authors load only when accessed
What It Enables

This lets your app run faster and use less memory by loading data smartly, improving user experience and scalability.

Real Life Example

When showing a list of blog posts, you load just the posts first (LAZY). Only when a user clicks a post, you load comments and details, saving bandwidth and speeding up the page.

Key Takeaways

Manual data loading can slow apps and waste resources.

LAZY fetch loads related data only when needed.

EAGER fetch loads all related data immediately.