Is JPA's n+1 problem related to @OneToMany or to @ManyToOne or both?

Sure there are many articles about n+1 JPA’s problem and also Q&As here, some of them discuss the problem from @OneToMany perspective, others from @ManyToOne is the problem relevant for both?

@OneToMany: when query entity from which have a field collection annotated @OneToMany

@ManyToOne: when query entity from which have a field annotated @ManyToOne

>Solution :

For both even for @OneToOne when it’s lazy loaded.

The problem occurs if you load a list of entities where the entities have relationships to one or more entities.

So the first query is getting the list and then for every entity in the list JPA will load the relationships with an additional query.

Leave a Reply