I am facing with 2 problems: N + 1 query and Out Of Memory (OOM).
I solved OOM by paging and lazy loading:
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Set<Employee> employees;
But when I use lazy loading, N + 1 query happened. So I try to use EntityGraph
as https://www.baeldung.com/spring-data-jpa-named-entity-graphs. But as my researches and local test, EntityGraph
always do eager loading for NamedAttributeNode
field - association field, which I want to be lazy loading - do not load all data at first:
@Entity
@Table(name = "department")
@NamedEntityGraph(name = "Department",
attributeNodes = {
@NamedAttributeNode("employees")
}
)
public class Department implements Serializable {
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Set<Employee> employees;
}
So are there any way to get them both ? Use EntityGraph
to avoid N + 1 and lazy loading to avoid OOM ?
UPDATE:
Can EntityGraph
works fine with Pageable effectively ? I mean do not load all data in JOIN query.