I have two classes, A and B with a One-To-Many relationship.
@Entity
public class A {
//some code
@OneToMany(fetch = FetchType.LAZY, mappedBy = "abc")
private List<B> b;
}
I have a JPA Repository for A, and I observed that when I fetch an A from the database with a repository method, Bs are not included. When I want to access Bs, additional SELECT queries are executed to fetch associated Bs(if there are 100 associated Bs, 100 additional queries are executed). making FetchType.EAGER only changes when these additional SELECT queries are executed. i.e. they are called right after the main SELECT query. Either way, additional SELECT queries are executed to fetch associated classes.
Is this natural behavior? I found that JPA Entity Graphs is the solution for this issue/to fetch A with Bs with a single SELECT query. Are there any other ways to address this issue? The problem with @EntityGraph
is it has to be annotated with each repository method separately. Also, is there a way to annotate @EntityGraph
once so it affects all the methods in the Repository?
I'm using Spring Boot 2.5.1. Thanks in advance!