0
0
SpringbootConceptBeginner · 3 min read

Fetch Type in JPA: What It Is and How It Works

In JPA, fetch type controls when related data is loaded from the database. It has two main options: EAGER loads related data immediately, while LAZY loads it only when accessed. This helps optimize performance by controlling data retrieval timing.
⚙️

How It Works

Imagine you have a photo album and you want to see the photos inside. Fetch type in JPA decides if you get all photos right away when you open the album, or only when you ask for a specific photo.

With EAGER fetch type, JPA loads all related data immediately, like opening the album and seeing all photos at once. This is simple but can slow down your app if there is a lot of data.

With LAZY fetch type, JPA waits until you actually ask for the related data before loading it, like opening the album but only looking at photos you want. This saves resources but needs careful handling to avoid errors.

💻

Example

This example shows a Book entity with a list of Author entities. The fetch type controls when authors are loaded.

java
import jakarta.persistence.*;
import java.util.List;

@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @OneToMany(fetch = FetchType.LAZY) // Change to EAGER to load authors immediately
    private List<Author> authors;

    // getters and setters
}

@Entity
public class Author {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    // getters and setters
}
Output
When fetching a Book: - With LAZY: authors are loaded only when book.getAuthors() is called. - With EAGER: authors are loaded immediately with the book.
🎯

When to Use

Use EAGER fetch type when you always need related data together, like a user profile and its settings. This avoids extra database calls.

Use LAZY fetch type when related data is large or rarely needed, like comments on a blog post. This improves performance by loading data only when necessary.

In real apps, LAZY is often preferred to keep the app fast and responsive, but it requires careful coding to avoid accessing unloaded data outside a database session.

Key Points

  • FetchType.EAGER: loads related entities immediately.
  • FetchType.LAZY: loads related entities on demand.
  • Choosing the right fetch type helps balance performance and convenience.
  • Lazy loading can cause errors if accessed outside a transaction.
  • Default fetch type depends on the relationship type in JPA.

Key Takeaways

Fetch type controls when JPA loads related data: immediately (EAGER) or on demand (LAZY).
Use EAGER when related data is always needed to reduce database calls.
Use LAZY to improve performance by loading data only when accessed.
Be careful with LAZY loading to avoid errors outside database sessions.
Default fetch type varies by relationship; always check JPA docs.