FetchType and Data Loading

Basic Java
≈ 2 min read

Related data does not always need to load at the same time

When JPA loads an Entity, it may have related objects and collections. Loading the entire graph immediately can be expensive, but postponing everything without exception is inconvenient too. Relationship mappings therefore use a fetching strategy.

EAGER and LAZY express different intentions

@ManyToOne(fetch = FetchType.LAZY)
private User user;

EAGER requires the related state to be available as part of loading the Entity. LAZY means loading may be postponed until the relationship is actually needed. The exact number of SQL queries is still determined by the provider and the query itself, not by a single annotation alone.

Fetching is part of query design

If a screen needs orders together with their users, those data should be fetched deliberately. If users are not needed at all, loading them only adds work. So FetchType is not a “fast/slow” switch, but part of deciding which data a particular scenario needs.

LAZY does not mean “there will definitely be fewer queries.” Careless access to deferred relationships can instead produce many additional queries — we will examine that later as the N+1 problem.