Sobes.tech
Middle

What is fetch type?

sobes.tech AI

Answer from AI

Fetch type in JPA determines how related entities are loaded from the database. There are two main types: EAGER and LAZY.

  • EAGER: The related entity is loaded together with the main entity on the first query. This is convenient when the related entity is almost always needed, but can lead to excessive data loading and performance degradation when there are many relations.

    // Example of EAGER loading
    @ManyToOne(fetch = FetchType.EAGER)
    private Address address; // Address will be loaded along with User
    
  • LAZY: The related entity is loaded only when it is first accessed (for example, when calling a getter). This allows avoiding loading unnecessary data but requires an additional database query each time the related entity is accessed, which can lead to the "N+1 select" problem.

    // Example of LAZY loading
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    private List<Order> orders; // Orders will be loaded only when user.getOrders() is called
    

Choosing the fetch type is a compromise between performance and convenience. For most collections (@OneToMany, @ManyToMany), LAZY is used by default, and for single relations (@ManyToOne, @OneToOne), EAGER is used by default, except when there is no @JoinColumn annotation on the owning side of @OneToOne, in which case it is also LAZY by default. It is recommended to use LAZY by default and switch to EAGER only when justified by requirements.

To optimize loading when using LAZY, JPQL/Criteria queries with FETCH JOIN or @NamedEntityGraph can be used.

What is fetch type? — Java - sobes.tech