Skip to main content

A Deep Dive into JPA Fetch Types: Exploring the Default Loading Strategy

When working with Java Persistence API (JPA), it's essential to understand the different fetch types for entity associations. In JPA, you can define the fetch type for relationships between entities, which determines how related entities are loaded from the database.

In JPA, the default fetch types for different mappings are as follows:

One-to-One Relationship

For a one-to-one relationship, the default fetch type is FetchType.EAGER. This means that the associated entity will be loaded from the database eagerly, along with the main entity.


@Entity
public class Author {
    // ...
    
    @OneToOne(fetch = FetchType.EAGER)
    private Address address;
    
    // ...
}

@Entity
public class Address {
    // ...
}
    

One-to-Many Relationship

For a one-to-many relationship, the default fetch type is FetchType.LAZY. This means that the associated entities will not be loaded from the database until explicitly accessed by your code.


@Entity
public class Order {
    // ...
    
    @OneToMany(fetch = FetchType.LAZY)
    private List items;
    
    // ...
}

@Entity
public class OrderItem {
    // ...
}
    

Many-to-One Relationship

For a many-to-one relationship, the default fetch type is FetchType.EAGER. This means that the associated entity will be loaded from the database eagerly when the main entity is loaded.


@Entity
public class OrderItem {
    // ...
    
    @ManyToOne(fetch = FetchType.EAGER)
    private Order order;
    
    // ...
}

@Entity
public class Order {
    // ...
}
    

Many-to-Many Relationship

For a many-to-many relationship, the default fetch type is FetchType.LAZY for both sides of the relationship. This means that the associated entities will not be loaded until you access the relationship in your code.


@Entity
public class Book {
    // ...
    
    @ManyToMany(fetch = FetchType.LAZY)
    private List authors;
    
    // ...
}

@Entity
public class Author {
    // ...
    
    @ManyToMany(mappedBy = "authors", fetch = FetchType.LAZY)
    private List books;
    
    // ...
}
    

Summary

In JPA, the default fetch types for different mappings are:

  • One-to-One: FetchType.EAGER
  • One-to-Many: FetchType.LAZY
  • Many-to-One: FetchType.EAGER
  • Many-to-Many: FetchType.LAZY
Understanding the default fetch types is crucial for optimizing performance and minimizing unnecessary database queries.

Comments