Sobes.tech
Junior — Middle

What is lazy loading in JPA and what are its advantages and disadvantages?

sobes.tech AI

Answer from AI

Lazy Loading in JPA is a mechanism where related entities or collections are not loaded from the database immediately when the main entity is loaded, but only upon the first access to them in the code.

Advantages:

  • Saves resources and time during loading if related data is not always needed.
  • Reduces the volume of data transferred and the load on the database.

Disadvantages:

  • Possibility of encountering a LazyInitializationException error if access to lazily loaded data occurs outside the EntityManager session context.
  • Potential increase in the number of SQL queries (N+1 problem).

Example of configuring lazy loading for a @OneToMany relationship:

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

Here, the list of books of the author will only load when accessing author.getBooks().

What is lazy loading in JPA and what are its… - sobes.tech