MODULE 6 - Advanced Spring Data JPA
Welcome to Module 6! π―β
In Module 2, you learned the basics of Spring Data JPA: the 4 CRUD methods (save, findById, findAll, deleteById) and 3 simple keywords (findBy, And, Or).
Now, you are ready to go further!
This module teaches you advanced JPA concepts to create complex queries and manage entity relationships.
π Learning Objectivesβ
By the end of this module, you will be able to:
- β Use the 15+ Spring Data JPA keywords
- β Create custom queries with @Query
- β Manage relationships (@OneToMany, @ManyToOne, @ManyToMany)
- β Use pagination and sorting
- β Optimize query performance
π Prerequisitesβ
Before starting this module, you should have:
- β Completed Modules 1 to 4
- β Mastered the basics of JPA (Module 2, Chapter 5)
- β
Understood repositories (
JpaRepository)
If these prerequisites are not met, go back to Module 2!
πΊοΈ Module Outlineβ
Theoretical Part (4 chapters)β
Chapter 1: Advanced Naming Conventionsβ
Duration: 1h
Content:
- The 15+ Spring Data JPA keywords
- Between, LessThan, GreaterThan
- Like, StartingWith, EndingWith, Containing
- In, NotIn, IsNull, IsNotNull
- True, False, IgnoreCase
- Practical examples for each keyword
Why important? Create complex queries without writing SQL
Chapter 2: Entity Relationshipsβ
Duration: 1h30
Content:
- @OneToOne (1-1)
- @OneToMany and @ManyToOne (1-N)
- @ManyToMany (N-N)
- Fetch types (LAZY vs EAGER)
- Cascade operations
- Bidirectional relationships
Why important? Model complex real-world data
Chapter 3: Custom Queries with @Queryβ
Duration: 1h
Content:
- JPQL syntax
- @Query with JPQL
- @Query with native SQL
- Named parameters with @Param
- Named queries
- Dynamic queries
Why important? Go beyond naming conventions
Chapter 4: Pagination and Performanceβ
Duration: 1h
Content:
- Pageable and
Page<T> - Sort and multi-criteria sorting
- N+1 problem
- Fetch strategies
- Projections
- Query optimization
Why important? Create high-performance applications
Practical Part (3 Labs)β
Lab 6.1: Advanced Conventionsβ
Duration: 2h
Objective: Master the 15+ keywords
You will create:
- Product entity with many fields
- 20 repository methods using the keywords
- Tests for each method
Lab 6.2: Employee-Department Relationshipsβ
Duration: 2h
Objective: Manage entity relationships
You will create:
- Employee and Department entities (OneToMany/ManyToOne)
- Complete CRUD with relationships
- Cascade operations
- Relationship tests
Lab 6.3: Airport-Flight-Passenger Exerciseβ
Duration: 2h30
Objective: Comprehensive assessment
You will:
- Model 3 related entities
- Implement 20 queries (Easy, Medium, Hard)
- Provided solution guide
- Self-assessment
π Total Durationβ
| Type | Duration |
|---|---|
| Theory | 4h30 (4 chapters) |
| Practice | 6h30 (3 Labs) |
| Total | 11h (~3-4 sessions) |
π― What You Will Learnβ
Before Module 6β
// You knew how to do this:
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByName(String name);
List<Product> findByNameAndPrice(String name, Double price);
}
Limited to: Simple queries with And and Or
After Module 6β
// You will know how to do all this:
public interface ProductRepository extends JpaRepository<Product, Long> {
// Comparisons
List<Product> findByPriceBetween(Double min, Double max);
List<Product> findByPriceLessThan(Double maxPrice);
List<Product> findByPriceGreaterThanEqual(Double minPrice);
// Text search
List<Product> findByNameContaining(String keyword);
List<Product> findByNameStartingWith(String prefix);
List<Product> findByDescriptionLike(String pattern);
// Lists and nulls
List<Product> findByCategoryIn(List<String> categories);
List<Product> findByDiscountIsNull();
List<Product> findByActiveTrue();
// Sorting and pagination
Page<Product> findByCategory(String category, Pageable pageable);
// Custom queries
@Query("SELECT p FROM Product p WHERE p.price < :maxPrice")
List<Product> findCheapProducts(@Param("maxPrice") Double maxPrice);
// Native SQL
@Query(value = "SELECT * FROM products WHERE stock < 10", nativeQuery = true)
List<Product> findLowStock();
}
You will master: Complex queries, relationships, performance!
π Why This Module Is Importantβ
1. Real-World Queries in Productionβ
In a company, you will NOT only do findAll(). You will need to:
// Find a customer's orders in the last 30 days
List<Order> findByCustomerIdAndOrderDateAfter(Long customerId, LocalDate date);
// Out-of-stock products in a category
List<Product> findByCategoryAndStockLessThan(String category, Integer minStock);
// Employees in a department with salary in a range
List<Employee> findByDepartmentAndSalaryBetween(Department dept, Double min, Double max);
This module prepares you for reality!
2. Application Performanceβ
Common issue: The N+1 Problem
// β Bad practice - N+1 queries!
List<Department> departments = departmentRepo.findAll(); // 1 query
for (Department dept : departments) {
List<Employee> employees = dept.getEmployees(); // N queries!
// ...
}
Solution you will learn:
// β
Good practice - 1 query!
@Query("SELECT d FROM Department d JOIN FETCH d.employees")
List<Department> findAllWithEmployees();
This module teaches you to write performant code!
3. Modeling Complex Dataβ
Real case: E-commerce
Customer ββ< Order >ββ Product
β
βββ> Payment
You will learn to:
- Model these relationships
- Manage cascades (delete a Customer β their Orders?)
- Optimize queries
- Handle orphaned data
πΊοΈ Training Progressionβ
Module 2: JPA Basics (4 methods, 3 simple keywords)
β
Module 6: β YOU ARE HERE - Advanced JPA
(15+ keywords, relationships, @Query, performance)
β
Projects: Complete applications with complex databases
Module 6 = Becoming an expert in Spring Data JPA!
π How to Approach This Moduleβ
Recommended Methodβ
-
Read the chapters in order
- Chapter 1: Conventions (15+ keywords)
- Chapter 2: Relationships (OneToMany, ManyToOne, etc.)
- Chapter 3: @Query (JPQL, native SQL)
- Chapter 4: Performance (pagination, optimization)
-
Do the labs progressively
- Lab 6.1: Practice conventions (2h)
- Lab 6.2: Practice relationships (2h)
- Lab 6.3: Comprehensive assessment (2h30)
-
Test all the code
- Do not copy, type the code
- Test each query
- Understand the results
Recommended Timeβ
Intensive Option (1 weekend):
- Saturday: Chapters 1-2 + Lab 6.1
- Sunday: Chapters 3-4 + Lab 6.2 + Lab 6.3
Progressive Option (3 sessions):
- Session 1: Chapters 1-2 + Lab 6.1
- Session 2: Chapter 3 + Lab 6.2
- Session 3: Chapter 4 + Lab 6.3
β Self-Assessmentβ
Before starting, test your knowledge:
- Do you know how to create a
findByPriceBetweenmethod? β Yes β No - Are you familiar with @OneToMany and @ManyToOne? β Yes β No
- Do you know how to use @Query? β Yes β No
- Do you understand the N+1 problem? β Yes β No
- Do you know how to paginate results? β Yes β No
If you answered "No" to 2 or more questions β This module is ESSENTIAL for you!
After the module, retake this test. You should answer "Yes" everywhere!
π― Next Stepβ
Ready to become an expert in Spring Data JPA?
β‘οΈ Start with Chapter 1: Advanced Naming Conventions