Friends of OpenJDK Today

A Walk to Lazy Fetching With Hibernate and Spring Data JPA

November 17, 2021



Using FetchType.EAGER is a very bad practice, since our services may not require all the data of the mapped entities in all cases. And moreover, it is a bad idea to fetch so much data in a single session and makes the session heavy.

Therefore we will refactor the code and use FetchType.LAZY.

Our old code for the entity was below:

Domain model with fetch type EAGER

After using FetchType.LAZY our new code will be like below:

Domain model with fetch type LAZY

But now when we try to build our project, we get a new problem. We have the LazyInitializationException.


Troubleshooting LazyInitializationException

There might be found many suggestions over online. But my preferred one (I found it really effective) is using something called EntityGraph.

A point to note, we can do it in 2 ways.

  1. One is using the annotations @NamedEntityGraphs, @NamedEntityGraph and @NamedAttributeNode annotations, which are provided by javax.persistence package.
  2. Using @EntityGraph annotation in repository interfaces. This annotation is provided by Spring Data JPA.

We will see both approaches here.

Using javax.persistence Provided Annotations

We will annotate our above mentioned Status entity with the annotations shown below.

Annotating the Entity with @NamedEntityGraph


Here, @NamedEntityGraphs annotation accepts an array of @NamedEntityGraph. So we can define as many entity graphs as we need.

In the @NamedEntityGraph annotation we have defined a name which we will call later. An "attributeNodes" attribute which we will use to mention the mapped entities we want to join for this named entity graph.

Notice that here we have only used the attributes owner and locations in our @NamedAttributeNode annotation, meaning that when we will call this named entity graph, the joined data will be fetched for these 2 attributes only and we will get no data for the attachments attribute.

Calling the named entity graph:

To call this named entity graph in our query, we have added the following additional lines (line 96, 97 and 101) in our existing code.

Calling the named entity graph

Using Spring Data JPA Provided @EntityGraph Annotation

Let’s see the entity first.

We have an entity which has a List of String Roles, mapped as @ElementCollection. Its fetch type is FetchType.LAZY.

Now let’s see our UserRepository interface.

Here we have used the @EntityGraph annotation and provided the attribute name which we want to fetch, in attributePaths parameter. And it is that simple to do the whole stuff.

The code for javax.persistence provided annotations can be found in this github repository.

Related Articles

View All
  • A Simple Service with Spring Boot

    I will demonstrate how to create a simple Web Service using Spring Boot.  This framework makes it almost effortless to develop web services, so long as the appropriate dependencies are in place.

    In this example, I will create a Web Service that will read the current temperature from a file and make it available to clients via a RESTful endpoint.

    Read More
    Avatar photo
    September 22, 2020
  • Annotation-free Spring

    Some, if not most, of our judgments regarding technology stacks come either from third-party opinions or previous experiences. Yet, we seem to be adamant about them!

    Read More
    Avatar photo
    September 17, 2021
  • Better Error Handling for Your Spring Boot REST APIs

    One of the things that distinguishes a decent API from one that is a pleasure to work with is robust error handling. Nothing is more frustrating than using some API and getting back cryptic errors where you can only guess why the server is not accepting your request.

    Spring Boot lets you customize the error handling for your application, but there is quite a lot of low-level coding involved if you want to do this correctly.

    Read More
    August 21, 2021


Comments (1)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Jpa Lazy? Best 7 Answer -

[…] + Read More Here […]

Subscribe to foojay updates:
Copied to the clipboard