Sobes.tech
Junior — Middle

How is lazy loading of related data implemented using FetchType.LAZY in JPA?

sobes.tech AI

Answer from AI

In JPA, the annotation FetchType.LAZY indicates that related data (such as collections or associated entities) should not be loaded immediately when loading the main entity, but only upon the first access to that data.

Lazy loading is typically implemented using proxy objects. When the main entity is loaded, JPA creates proxies for related fields, which do not contain actual data but only information on how to load it.

When the code accesses such a field (for example, calling a method or iterating over a collection), the proxy automatically executes a database query to load the necessary data.

Example:

@Entity
public class Author {
    @OneToMany(fetch = FetchType.LAZY)
    private List<Book> books;

    // getters and setters
}

// When loading Author, books are not loaded immediately
Author author = entityManager.find(Author.class, 1L);

// On the first call to author.getBooks(), a database query is executed to load the books
List<Book> books = author.getBooks();

Thus, FetchType.LAZY helps optimize performance by loading related data only when necessary.