Collection Associations Should Not Use Eager Fetching
ID |
java.hibernate_collections_must_be_lazy |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency, hibernate, orm |
Description
Reports collection-valued associations (@OneToMany, @ManyToMany, @ElementCollection) that explicitly set fetch = FetchType.EAGER. Eagerly fetching collections loads all associated entities immediately with the owning entity, often leading to N+1 query problems, excessive memory usage, and unpredictable performance degradation as data grows.
Rationale
When a collection association is marked EAGER, Hibernate loads the entire collection every time the parent entity is fetched, regardless of whether the collection is actually used. For @OneToMany and @ManyToMany relationships, this can cascade into loading thousands of rows and their transitive associations.
// Bad: eager-fetching a collection
@Entity
public class Department {
@Id
private Long id;
@OneToMany(fetch = FetchType.EAGER)
private List<Employee> employees;
}
Loading a single Department also loads every Employee, which may in turn eagerly load their own associations, creating a cascade of queries.
Remediation
Remove the explicit fetch = FetchType.EAGER attribute or set it to FetchType.LAZY. Use JOIN FETCH in JPQL queries or entity graphs when the collection is needed for a specific use case.
// Good: lazy-fetching (default for @OneToMany)
@Entity
public class Department {
@Id
private Long id;
@OneToMany
private List<Employee> employees;
}