Skip to content

sovanmukherjee/spring-boot-jpa-entity-graph

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Getting Started

Reference Documentation

For further reference, please consider the following sections:

Guides

The following guides illustrate how to use some features concretely:

Additional Links

These additional references should also help you:

Overview

We can use EntityGraph to formulate better-performing queries and deal with performance loading.

In this application Status, subStatuses and address are loaded lazily. The method findAll of UserRepository return UserEntity from user table data with single query. But when we are calling getStatus() of UserEntity it will call one more select query and again it will generate new query when we will call getSubStatuses() of StatusEntity, Similarly for getAddress it will generate +1 query.

Here is table and data.

User Table:

image

Status Table:

image

SubStatus Table:

image

Address Table:

image

Without EntityGraph:

findAll() method of UserRepository: image Below is the Test Result screenshot, we can see there are 9 queries generated. image

1st query to get user list.
3 status table query by 3 status Ids(1,2,3).
3 SubStatus table query by substatus ids(1,2,3) and
2 address table query by address ids(1,2).

So, If we have huge data then number of query will be increase.

API response time without EntityGraph: 26.0ms image

This can be easily achieved by 1 query using join. We can use EntityGraph with different FetchType Strategies to achieve this.

Fetch(EntityGraph.EntityGraphType.FETCH): The attributes that are specified by attributeNodes are treated as FetchType.EAGER and the rest of the attributes are treated as FetchType.LAZY

Load(EntityGraph.EntityGraphType.LOAD): The attributes that are specified by attributeNodes are treated as FetchType.EAGER and the rest of the attributes are treated according to their specified or default FetchType

It defaults to EntityGraph.EntityGraphType.FETCH.

With EntityGraph:

findAll() method of UserRepository: image

Below is the Test Result screenshot with EntityGraph image Here we are seeing there is 1 query generated using left outer join

API response time with EntityGraph: 14.3ms image

How to provide graph name dynamically?

  1. You can use https://github.com/Cosium/spring-data-jpa-entity-graph
    Add in build.gradle file: image

  2. Add EnableJpaRepositories in configuration or main class image

  3. Extends EntityGraphJpaRepository and EntityGraphJpaSpecificationExecutor in repository interface image

  4. Provide different graph name from service class image

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages