Sobes.tech
Middle

What does FetchType.LAZY mean in JPA and how does it affect the loading of related entities?

sobes.tech AI

Answer from AI

FetchType.LAZY in JPA means lazy loading of related entities. Instead of loading the entire related collection or a separate entity when retrieving the main entity, JPA creates a proxy object. The actual data loading from the database occurs only when first accessing the proxy's fields or methods.

This allows:

  • Performance optimization: Avoid retrieving large amounts of data from the database when they are not used.
  • Reduce memory consumption: Load only the necessary data.

By default, most relationships (@OneToMany, @ManyToMany) use FetchType.LAZY, while @OneToOne and @ManyToOne use FetchType.EAGER. You can explicitly specify the fetch type:

// Example of using FetchType.LAZY
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private Set<ChildEntity> children;

@ManyToOne(fetch = FetchType.LAZY)
private ParentEntity parent;

Problems with FetchType.LAZY:

  • LazyInitializationException: Can occur if you try to access a lazily loaded entity after the session in which it was loaded has been closed.
  • N+1 problem: If you iterate over a collection of entities with lazy loading and access each related entity, a separate query to the database will be executed for each entity in the collection.

To solve these problems, you can use:

  • Explicitly fetching related data using JOIN FETCH in JPQL:

    // Example of JOIN FETCH
    SELECT p FROM ParentEntity p JOIN FETCH p.children WHERE p.id = :parentId
    
  • JPA provider settings (e.g., batching).

  • Hibernate annotations @Fetch(FetchMode.JOIN) or @Fetch(FetchMode.SELECT).