Hibernate Lazy vs Eager loading Example

In this tutorial, we will see JPA/Hibernate Lazy vs Eager loading Example using Spring Boot and Oracle.

Important points about Hibernate Lazy and Eager loading.

We use the fetch type(Lazy and Eager loading) for association mapping –  For example, for below association mapping we can define fetch type.

  • OneToOne mapping.
  • OneToMany mapping.
  • ManyToOne mapping
  • ManyToMany mapping
  • ElementCollection(used for embeddable objects). See an example about @ElementCollection.

Lazy loading(fetch = FetchType.LAZY) –  We can define fetch type for OneToMany mapping as @OneToMany(fetch = FetchType.LAZY). The FetchType.LAZY loads child entity lazily or when it needed(on demand). What does it mean?

Consider we have two entity Book.java and Story.java which are mapped in OneToMany relationships. One Book can have multiple stories.

 

Story.java

 

When we load a Book entity from the database, Hibernate will not load Story entities unless we will not do book.getStoryList();.  Since we have  @OneToMany(fetch = FetchType.LAZY) with storyList field.

Eager loading for Hibernate Eager vs Lazy loading Example and also we will later query.

Eager loading(fetch = FetchType.EAGER) – When we define fetch type is EAGER it will load child entities along with parent entity. For example, consider one Book has five stories, if we do @OneToMany(fetch = FetchType.EAGER) we will have five story entities along with Book entity. We will see later in details.

 

Default Fetch type in case of the below annotations.

@OneToOne – Default fetch type is EAGER
@OneToMany – Default fetch type is LAZY.
@ManyToOne – Default fetch type is EAGER.
@ManyToMany – Default fetch type is LAZY.
@ElementCollection – Default fetch type is EAGER.

 

Query Creation in case of Lazy and Eager loading.

In the case of fetch = FetchType.LAZY if we try to fetch Book entity, two separate queries will get generated. One for Book entity and another for Story entities. 

For fetch = FetchType.EAGER if we try to fetch Book entity, Only one query will get generated with JOIN. We will see in details at the end of the post.

 

When to use lazy loading and Eager loading.

Consider we have Book and Story entity in OneToMany relationship and One Book contains a hundred or thousands Story entity. In this case, defining fetch = FetchType.EAGER might not a good idea. It will fetch all child(Story) entities along with Book entity. This might impact performance. We can define fetch type Lazy when the possibility of child entities records are more in number.

For OneToOne and ManyToOne default load type is Eager most of the time it’s better to leave it Eager only since we have OneToOne association.

Summary – There is no straight forward rule to decide when to use Lazy or Eager fetch Type. After knowing the application and entities and data(number of the possible child entities) we can decide to use Lazy or Eager fetch Type.

 

LazyInitializationException – Failed to lazily initialize a collection of role could not initialize proxy – no Session.

When you working with association mapping you may encounter LazyInitializationException could not initialize proxy – no Session. This exception comes when two entities are in association mapping with fetch= FetchType.LAZY and we try to get child entity from the parent entity after the session gets closed. 

We have a separate and detailed post, how to fix this using a different approach.

we will see JPA/Hibernate Eager vs Lazy Fetch Type Example using Spring Boot and Oracle.

Hibernate Lazy vs Eager loading Example Using Spring Boot and Oracle.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – fetchtype, ArtifactId – fetchtype and name – fetchtype) and click on finish. Keep packaging as the jar.

Modify the pom.xml with the below code.

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

 

Define entity class i.e Book.java and Story.java.

Book.java

Story.java

 

Define the repository interface extending CrudRepository.

BookRepository.java

Define service interface i.e BookService.java

Define service implementation class.

BookServiceImpl.java

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

Define the controller class or endpoint.

BookController.java

Note – See more details about @Controller and RestController here.

Define the JpaConfig.java

Step 12 – Define the SpringMain.java

 

And finally, we have an application.properties file where we have database details.

application.properties

We are almost done. Just build the project once running the main method. Open git bash or cmd and Run mvn clean install.

Let’s deploy the application running SpringMain class as a java application.

JPA/Hibernate Eager vs Lazy loading Example using Spring Boot

Let’s see testing for JPA/Hibernate Eager vs Lazy Fetch Type Example using Spring Boot and Oracle.

Testing of example and query generated in both cases.

Sample request JSON data to perform save operation.

http://localhost:9091/book/savebook

JPA/Hibernate Eager vs Lazy loading Example using Spring Boot

 

GET – http://localhost:9091/book/3

Query Generated in case of fetch = FetchType.LAZY while fetching Book entity.

 

Query Generated in case of fetch = FetchType.EAGER while fetching Book entity.

 

Observe both cases. In the case of fetch = FetchType.LAZY there are two separate queries getting prepared while in case of fetch = FetchType.EAGER only one query with Left Outer Join.

 

Note – There is an enum FetchType called in javax.persistence.

 

That’s all about JPA/Hibernate Lazy Vs Eager loading/Fetch Type Example using Spring Boot.

You may like.

Other Tutorial.

Fetch type docs.

Summary –  We have seen about Hibernate Eager vs Lazy loading Example. The fetch = FetchType.LAZY allow fetching child entity on demand. The fetch = FetchType.EAGER will load child entity along with parent.

 

 

 

 

Top