Skip to content

Module 2: Repositories (The Automatic Clerk)

📚 Module 2: Spring Data Repositories

Focus: Moving from “Writing Queries” to “Using Interfaces.”

In Milestone 2, you learned that an Interface is a Contract. Spring Data JPA uses interfaces to automatically write database queries for you.


🏗️ Step 1: The JpaRepository (The “Super Clerk”)

You don’t need to write code to “Find all products” or “Delete by ID.” You just tell Spring you want a JpaRepository.

🧩 The Analogy: The Automatic Warehouse Clerk

  • Imagine you have a clerk at the warehouse door.
  • You don’t tell the clerk “Walk to row 5, look for item 12, pick it up…”.
  • You just say: “Find item 12.”
  • Because the clerk follows the Standard Procedure (The Repository Interface), they know exactly how to do it.

In Code:

public interface ProductRepository extends JpaRepository<Product, Long> {
    // You get findAll(), save(), findById(), and delete() for FREE!
}

🏗️ Step 2: Query Methods (The “Magic Names”)

One of the coolest features of Spring is that it can write custom SQL based on the Name of the method.

🧩 The Analogy: The Listening Robot

  • If you name your method findByName, Spring thinks: “Okay, they want a SELECT where NAME equals the input.”
  • If you name it findByPriceGreaterThan, Spring writes: “SELECT * FROM products WHERE price > …”.

In Code:

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByName(String name);
    List<Product> findByPriceGreaterThan(Double minPrice);
}

🏗️ Step 3: Why use Repositories?

  1. Zero Boilerplate: You don’t have to write thousands of lines of JDBC code.
  2. Consistency: Every part of your app uses the same standard methods to talk to the database.
  3. Speed: You can build a full data layer in about 30 seconds.

🥅 Module 2 Review

  1. JpaRepository: The base interface that gives you standard CRUD (Create, Read, Update, Delete) for free.
  2. Query Methods: Defining methods by name to let Spring write the SQL.
  3. Generic Types: JpaRepository<Product, Long> tells Spring: “This is for the Product entity, and its ID is a Long.”