Skip to content

Fetching Strategies (Eager Loading vs. Lazy Loading)

Now, when it comes to fetching data, there are two main strategies: Eager Loading and Lazy Loading. Think of Eager Loading as grabbing all your ingredients at once, whether you need them immediately or not. It's like filling up your shopping cart with everything on your list right from the start.

On the other hand, Lazy Loading is a bit more laid-back. It's like strolling through the market, only picking up what you need when you need it. With Lazy Loading, Hibernate fetches data from the database only when it's absolutely necessary, which can save time and resources.

Example

Imagine you have two entity classes: Author and Book. An author can have multiple books associated with them.

java
public class Author {
    private Long id;
    private String name;
    private List<Book> books;

    // Getters and setters
}

public class Book {
    private Long id;
    private String title;
    private Author author;

    // Getters and setters
}

Now, let's see how Eager Loading and Lazy Loading work in action.

Eager Loading Example:

java
@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "author", cascade = CascadeType.ALL)
    private List<Book> books;

    // Getters and setters
}

In this example, when you fetch an Author object, Hibernate will automatically retrieve all associated Book objects eagerly. So, if you retrieve an Author, you'll also get all their books loaded immediately.

Lazy Loading Example:

java
@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "author", cascade = CascadeType.ALL)
    private List<Book> books;

    // Getters and setters
}

In this case, with Lazy Loading, Hibernate won't fetch the associated Book objects when you retrieve an Author object. Instead, it will wait until you explicitly access the books property. So, if you only need the author's information and not their books, Lazy Loading helps avoid unnecessary database queries until you actually need the book data.

These examples showcase how Eager Loading and Lazy Loading behave in Hibernate, offering different approaches to fetching associated data depending on your application's needs.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.