How to use Hibernate Lazy Fetch and Eager Fetch Type – Spring Boot + MySQL

How to use Hibernate Lazy Fetch and Eager Fetch Type – Spring Boot + MySQL

In the tutorial, Grokonez will help you understand Hibernate Lazy Fetch Type and Eager Fetch Type by sample code with Spring Boot & MySql database.

Related articles:
How to configure Spring JPA One to Many Relationship – SpringBoot
How to start development with Hibernate – XML Mapping File Hibernate

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE
– MySql database

II. Hibernate Lazy Fetch & Eager Fetch Type

How to load all entities of relationships in RDBMS Database?
-> Hibernate provides 2 strategies to retrieve entities(records) of all relationships: Lazy Fetch & Eager Fetch. So Hibernate Fetch Types are always associated with relationship annotations: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany.

1. Eager Fetch Type

Hibernate Eager Fetch Type comes with setting: fetch = FetchType.EAGER.

Hibernate Eager Fetch Type will load all the relationship entities at the initial time.

– Example, when calling companyRepository.findAll(), all the records of product tables will be loaded by Hibernate and stored in Set products of a Company object.



From the logs, having three select statements when calling function: companyRepository.findAll() to load company entities and all relationship entities: products at initial time. Then for next processing step(showing them on console), all info of product entities are ready in memory for getting.

*** Note: should consider about memory & performance issues when working with Eager fetching strategy.

2. Lazy Fetch Type

Hibernate Lazy Fetch Type comes with setting: fetch = FetchType.LAZY.


Hibernate Eager Fetch Type will NOT load any entities (records) of relationships at the initial time.
Need @Transaction annotation for Lazy Fetch to associate relationship loaded entities with a Hibernate session. If NOT, an exception will be thrown:

Details company loading service:

Logs when calling the function: companyRepository.findAll():

Difference with Eager Fetch, at retrieving Company entities step, just having one select statement to load company entities while invoking the function: companyRepository.findAll().
When showing relationship entities(products) info, having 2 others select statements to load product records from database.

III. Practice

Step to do:
– Create SpringBoot project
– Create Models
– Create JPA Repositories
– Implement Services
– Configure Datasource & Spring JPA
– Implement a test Client
– Run & Check results

1. Create SpringBoot project

– Using SpringToolSuite, create a SpringBoot project. Then add needed dependencies:

2. Create Models

2 Entities Company and Product that having One-to-Many relationship:

Spring Jpa One To Many Relationship

2.1 Company entity

2.2 Product entity

@Entity: Specifies that the class is an entity. This annotation is applied to the entity class.
@Id: Specifies the primary key of an entity.
@OneToMany: Defines a many-valued association with one-to-many multiplicity.
@ManyToOne: Defines a single-valued association to another entity class that has many-to-one multiplicity
@JoinColumn: Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

3. Create JPA Repositories

Create 2 interface repositories by extends JpaRepository:

4. Implement Services

About showData() function, we must implement with @Transactional for Lazy Fetch Type. But @Transactional is optional with Eager FetchType.

5. Configure Datasource & Spring JPA

Open, configure spring.datasource & spring.jpa:

6. Implement a test Client

Use 2 repository: CompanyRepository & ProductRepository

Implement 3 functions:
clearData() is used to empty 2 tables company & product
saveData() is used to persist entities (Company & Product) to database
showData() is used to load all records (Company & Product) and show all on console.

Full SourceCode:

7. Run & Check results
7.1 Run with Eager Fetch Type

Build & Run the project with SpringBoot App mode.
The sourcecode is ready with Eager Fetch Type config for both Company & Product.

7.2 Run with Lazy Fetch Type

Change the Fetch Type to LAZY for both: Company & Product.

– Build & Run again the project with SpringBoot App mode.

7.3 Mix Lazy & Eager Fetch Types

Change fetch type: Company with FetchType.LAZY BUT Product with FetchType.EAGER.

Build & Run again the project with SpringBoot App mode.


IV. Sourcecode


By grokonez | April 27, 2017.

Last updated on April 24, 2019.

Related Posts

2 thoughts on “How to use Hibernate Lazy Fetch and Eager Fetch Type – Spring Boot + MySQL”

  1. Thanks for this article. But what if I just want to return a company with products data to my controller for example. How would I do this?

    public Company showData(){
    Company company = companyRepository.findById(1).get();
    //; –> I must print in order to get all products
    return company

    Then I tried

    public Company showData(){
    Company company = companyRepository.findById(1).get();
    company.getProducts(); // My thinking is if company still retain session with db if I do this it just trigger a join fetch but it doesn’t… I must implement System.print or logger… to get products.
    return company;

    Maybe is just my logic problem but if you could kindly explain why printing the object or toString the object triggers the fetch. Thank you

Got Something To Say:

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