Hello,
I have the following relationships: A Sponsor has many Events, and an Event belongs to one Sponsor.
Code:
@Entity
@Table(name = "sponsors")
public final class Sponsor {
@OneToMany(mappedBy = "sponsor", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Event> events = new HashSet<>();
\\...
}
@Entity
@Table(name = "events")
public final class Event {
@ManyToOne(fetch = FetchType.LAZY)
@NotNull private Sponsor sponsor;
\\...
}
Even though I place an explicit Lazy FetchType annotation on Sponsor, I encounter an N+1 problem.
Whenever all events are being fetched, an additional SQL query will be invoked — fetching each Event’s Sponsor. So if I have 5 events, I’ll encounter 5 additional queries
Below is my JPA CriteriaBuilder query (generic):
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(clazz);
Root<T> root = query.from(clazz);
query.select(root);
return entityManager.createQuery(query).getResultList();
I’ve tried adding optional = false
to my @ManytoOne
annotation, as well as a @Fetch(FetchMode.JOIN)
annotation, but neither work.
Is this a bug? Is there a simple way to solve this issue?
Any help would be greatly appreciated.
Best,
Ron