Open In App

Hibernate – Eager/Lazy Loading

FetchType is an enumerated type in the Java Persistence API (JPA) that specifies whether the field or property should be lazily loaded or eagerly loaded. It is used in the javax.persistence.FetchType enum. In Hibernate, the FetchType is used to specify the fetching strategy to be used for an association. The FetchType can be specified for associations at the time of mapping the association. There are two FetchType options available: LAZY and EAGER.

 

Note: You can specify the fetch type of an association by using the fetch attribute of the @OneToMany, @ManyToOne, @OneToOne, or @ManyToMany annotations.



Overview

LAZY:




@Entity
public class Employee {
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "address_id")
    private Address address;
  
    // other fields and methods
}

Note: In this example, the Address entity associated with an Employee will be fetched lazily when it is accessed for the first time.



EAGER:




@Entity
public class Employee {
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "address_id")
    private Address address;
  
    // other fields and methods
}

Note: In this example, the Address entity associated with an Employee will be fetched eagerly when the Employee is loaded from the database.

Summary


Article Tags :