Appearance
Difference between FetchType LAZY and EAGER in Java Persistence API?
In the Java Persistence API (JPA), the FetchType enum is used to specify the strategy for fetching data from the database. There are two values of FetchType: LAZY and EAGER.
The LAZY fetch type specifies that the data should be fetched lazily, which means that the data is fetched when it is needed. This can be more efficient in cases where the data is not needed immediately, because it avoids the overhead of fetching the data upfront.
The EAGER fetch type specifies that the data should be fetched eagerly, which means that the data is fetched when the parent entity is fetched. This can be more efficient in cases where the data is needed immediately, because it avoids the overhead of fetching the data later.
You can use the FetchType enum with the @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany annotations to specify the fetching strategy for relationships between entities. Note that @ManyToOne and @OneToOne default to EAGER, while @OneToMany and @ManyToMany default to LAZY. For example:
java
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany;
import java.util.List;
@Entity
public class Post {
@OneToMany(fetch = FetchType.LAZY)
private List<Comment> comments;
}In this example, the comments field is a List of Comment entities that is fetched lazily. This means that the Comment entities will be fetched when they are needed, rather than when the Post entity is fetched.
For a contrasting example using @ManyToOne with EAGER fetching:
java
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToOne;
@Entity
public class Comment {
@ManyToOne(fetch = FetchType.EAGER)
private Post post;
}Note: This example uses jakarta.persistence imports, which are standard in Jakarta EE 9+ and Hibernate 6+. For older Java EE 8 environments, replace jakarta with javax.
It's important to note that FetchType defines the default fetching strategy, but JPA providers often optimize queries behind the scenes (e.g., using batch fetching or join fetching). However, if you access a LAZY association outside an active persistence context, the provider will throw a LazyInitializationException. You can trigger lazy loading explicitly by accessing the collection or entity, or handle the exception by ensuring the session is open or using JOIN FETCH in JPQL.