0
0
Spring Bootframework~30 mins

Join fetch for optimization in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Join Fetch for Optimization in Spring Boot
📖 Scenario: You are building a Spring Boot application that manages authors and their books. Each author can have multiple books. You want to fetch authors along with their books efficiently to avoid performance issues.
🎯 Goal: Learn how to use @Query with JOIN FETCH in Spring Data JPA to optimize fetching related entities in one query.
📋 What You'll Learn
Create an Author entity with a list of Book entities
Create a Spring Data JPA repository for Author
Add a configuration variable to control fetching behavior
Write a repository method using JOIN FETCH to fetch authors with their books in one query
💡 Why This Matters
🌍 Real World
Fetching related data efficiently is important in real-world applications to reduce database load and improve performance.
💼 Career
Understanding join fetch queries and Spring Data JPA repositories is essential for backend developers working with Spring Boot and relational databases.
Progress0 / 4 steps
1
Create Author and Book Entities
Create two entities: Author and Book. In Author, add a field List books with @OneToMany(mappedBy = "author"). In Book, add a field Author author with @ManyToOne. Use exact class and field names.
Spring Boot
Need a hint?

Remember to use @Entity on both classes and map the relationship correctly with @OneToMany and @ManyToOne.

2
Add Repository Interface for Author
Create an interface AuthorRepository that extends JpaRepository<Author, Long>. Add a boolean variable fetchBooks in your service or config class to control whether to fetch books eagerly or lazily.
Spring Boot
Need a hint?

Create the repository interface with the exact name AuthorRepository and extend JpaRepository<Author, Long>. Add the boolean variable fetchBooks exactly as shown.

3
Add Repository Method with Join Fetch
In AuthorRepository, add a method List<Author> findAllWithBooks() annotated with @Query that uses SELECT a FROM Author a JOIN FETCH a.books to fetch authors with their books in one query.
Spring Boot
Need a hint?

Use @Query annotation with the exact JPQL query SELECT a FROM Author a JOIN FETCH a.books and method name findAllWithBooks().

4
Use the Join Fetch Method Conditionally
In your service class, write a method List<Author> getAuthors() that returns authorRepository.findAllWithBooks() if AuthorServiceConfig.fetchBooks is true, otherwise returns authorRepository.findAll(). Use exact method and variable names.
Spring Boot
Need a hint?

Use the boolean fetchBooks to decide which repository method to call inside getAuthors().