Categories: Java, JPA

How to load nested JPA entities in a single query

jpa-fetch-joinsHave you ever realized that many times when accessing a managed entity’s attribute it’s common to see JPA performing many subsequent queries in the database in order to lazy load information? Well, it’s a good default behavior and works in the majority of the cases but still sometimes we need to modify this behavior on an ad hoc basis or per use case scenario. For these specific situations we can use a handy feature from JPA known as Fetch Joins. In a very abstract way we can say that the Fetch Joins allow us to dynamically define which relations we want to eagerly load when making a query. In this article we are going to retrieve nested JPA entities in a single query avoiding many database calls.

Example

Let’s consider the following example:

Our system has two entities: Customer and Address. The relationship between them is a bidirectional one-to-many from Customer to Address, which means that a Customer can have none or multiple instances of Address.