JPA and its implementation, Hibernate, is the most popular way to access relational data in Java applications. From the very beginning, data access optimization has been one of the main goals of Hibernate developers. One such optimization is eliminating unnecessary database queries, which significantly impact performance. For example, when dealing with related entities, such as master-detail relationships, we need to decide whether we need to fetch details. The simplest solution would be to mark associated entity fields with the EAGER fetch type. However, this is highly ineffective since we don’t always need associated entities. While LAZY fetching helps to avoid extra queries, it is essential to remember to fetch additional detail entities strictly within the transaction. Also, this may cause the N+1 query problem.
The Entity Graph specification was introduced in JPA 2.1, offering developers fine-grained control over how entities and their related data are fetched from the database. With entity graphs, developers can define explicit fetch plans, reducing the N+1 query problem and eliminating the need for manual JOIN clauses. This feature empowers developers to optimize data retrieval efficiently.