What is the difference between FetchType.Eager and FetchType.Lazy?

FetchType.EAGER and FetchType.LAZY control when JPA loads an entity's related data -- EAGER loads the associated entity or collection immediately, in the same query or a follow-up query right away, while LAZY defers loading the association until it's actually accessed in code.

Key Points: • EAGER guarantees the related data is available immediately but can hurt performance by loading data that ends up unused, and can trigger the N+1 query problem across collections. • LAZY loads the association on first access via a proxy, which improves performance when the related data isn't always needed, but requires an active persistence context/transaction at access time or it throws a LazyInitializationException. • @ManyToOne and @OneToOne default to EAGER; @OneToMany and @ManyToMany default to LAZY. • Fetch joins in JPQL (JOIN FETCH) let you eagerly load a lazy association for one specific query without changing the entity's default fetch type globally. • The general best practice is to default associations to LAZY and eagerly fetch only when a specific use case needs it, keeping the base entity mapping efficient.

Example: An Order entity's list of OrderItems is typically mapped LAZY since not every use case needs the items, but a specific "order details" screen that always needs both the order and its items can use a JOIN FETCH query to eagerly load them in one round trip just for that case.

Code Example:

@Entity
public class Order {
    @Id @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
    private List<OrderItem> items;
}

// Eagerly fetch just for this query, without changing the default mapping
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
Order findByIdWithItems(@Param("id") Long id);

Interview Tip: A concise interview answer is:

"EAGER loads the related entity or collection immediately along with the parent, while LAZY defers loading until the association is actually accessed, using a proxy. I default associations to LAZY to avoid loading data I don't need and to prevent N+1 problems, then use a JOIN FETCH in specific queries when I know I'll need the related data eagerly for that particular use case."