Skip to main content

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:

  1. βœ… Use the 15+ Spring Data JPA keywords
  2. βœ… Create custom queries with @Query
  3. βœ… Manage relationships (@OneToMany, @ManyToOne, @ManyToMany)
  4. βœ… Use pagination and sorting
  5. βœ… 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​

TypeDuration
Theory4h30 (4 chapters)
Practice6h30 (3 Labs)
Total11h (~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​

  1. 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)
  2. Do the labs progressively

    • Lab 6.1: Practice conventions (2h)
    • Lab 6.2: Practice relationships (2h)
    • Lab 6.3: Comprehensive assessment (2h30)
  3. Test all the code

    • Do not copy, type the code
    • Test each query
    • Understand the results

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:

  1. Do you know how to create a findByPriceBetween method? ☐ Yes ☐ No
  2. Are you familiar with @OneToMany and @ManyToOne? ☐ Yes ☐ No
  3. Do you know how to use @Query? ☐ Yes ☐ No
  4. Do you understand the N+1 problem? ☐ Yes ☐ No
  5. 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


⬅️ Back to Course Outline