Loading related entities with JPA and Hibernate is a comfortable feature that is also the most common reason for performance issues. In most applications you can find one of these two issues:
- related entities are eagerly loaded, even if they are not needed or
- related entities are lazily loaded which creates n+1 select issues if they are needed.
The first one can be easily fixed by changing the FetchType of a relationship to LAZY. But that often leads directly into the second issue. If you do not handle lazy relationships between entities in the right way, you will get n+1 select issues which will also slow down your application.
But these can be easily fixed as I show you in this free, 3-part mini course.
In the first part of this course, I explain what the n+1 select issue and how you can use Hibernate to find these issues during development.
In the second part, I show you how to use @NamedEntityGraphs to fix n+1 select issues by defining a graph of entities which will be fetched from the database.
In the third and final part, I show you how to dynamically define Entity Graphs at runtime.