Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 36

    Repository Pattern

    The repository pattern hides persistence behind an intention-revealing interface.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    The repository pattern hides persistence behind an intention-revealing interface. Services ask orders.activeFor(userId); they do not embed SQL, EntityManager details, or table names. Spring Data's JpaRepository already is a repository — extend it for simple domains.

    In stricter hexagonal / DDD Orders designs, the domain defines OrderRepository with domain types (OrderId), and an adapter implements it with Spring Data + mappers. That keeps Hibernate out of the domain model and eases testing with fakes.

    Do not invent repositories that leak sessions or return open streams to controllers. Keep query language choices (JPQL vs native) inside the adapter. Transactions still start in the application service that orchestrates use cases.

    Choose the depth of abstraction for your team's size: Spring Data interfaces first; custom ports when the domain must stay persistence-ignorant.

    Purpose of this lesson

    Apply the repository pattern to Orders — from Spring Data interfaces to optional hexagonal adapters that hide JPA.

    Understanding the topic

    Repositories speak domain intent; adapters speak JPA.

    • Spring Data: interface extends JpaRepository — fastest path.
    • Domain port: interface in domain; no Jakarta imports.
    • Adapter: @Repository implementation using Spring Data + mapper.
    • Testing: fake in-memory repo for service unit tests.
    • Boundary: services depend on ports, not SQL.

    Step-by-step explanation

    1. Start with OrderRepository extends JpaRepository<Order, Long> for the Orders service.
    2. When domain isolation is required, extract a port interface with domain methods.
    3. Implement JpaOrderRepository adapter that maps entities ↔ domain.
    4. Unit-test OrderService against an in-memory fake repository.

    Informative example

    Hexagonal-style Orders repository port + JPA adapter.

    java
    // Domain port (no jakarta imports)
    public interface OrderRepository {
    Optional<Order> byId(OrderId id);
    Order save(Order order);
    List<Order> activeFor(UserId userId);
    }
    // Spring Data entity repo (infrastructure)
    public interface JpaOrderEntityRepository extends JpaRepository<OrderEntity, Long> {
    List<OrderEntity> findByUserIdAndStatus(Long userId, String status);
    }
    @Repository
    public class JpaOrderRepository implements OrderRepository {
    private final JpaOrderEntityRepository jpa;
    private final OrderMapper mapper;
    public JpaOrderRepository(JpaOrderEntityRepository jpa, OrderMapper mapper) {
    this.jpa = jpa;
    this.mapper = mapper;
    }
    @Override
    public Optional<Order> byId(OrderId id) {
    return jpa.findById(id.value()).map(mapper::toDomain);
    }
    @Override
    public Order save(Order order) {
    return mapper.toDomain(jpa.save(mapper.toEntity(order)));
    }
    @Override
    public List<Order> activeFor(UserId userId) {
    return jpa.findByUserIdAndStatus(userId.value(), "PENDING")
    .stream().map(mapper::toDomain).toList();
    }
    }

    Real-world use

    TechLearningPRO starts with Spring Data repositories. When the billing bounded context needs the same order rules without dragging Hibernate into domain tests, the team introduces a port + JPA adapter — services and use-case tests stay free of EntityManager.

    Security implications

    Repositories concentrate data access — a natural control point.

    • Encode tenant/user constraints in repository methods used by 'my orders'.
    • Do not expose generic 'run this JPQL' methods on ports.
    • Audit adapters that execute native SQL for sensitive reports.

    Best practices

    • Begin with Spring Data; introduce ports when persistence ignorance pays rent.
    • Name methods after domain questions (activeFor), not SQL verbs alone.
    • Keep mapping code next to the adapter, not in the service.

    Common mistakes

    • Calling the pattern 'repository' while returning JPA entities from controllers.
    • Leaking EntityManager through the domain interface.
    • Over-abstracting a CRUD app into four layers before there is a second persistence technology.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat problem does the repository pattern solve?+

    Answer

    It decouples domain/application logic from persistence technology so services depend on intent-focused interfaces.
    2IntermediateQuestionIs Spring Data's JpaRepository already a repository?+

    Answer

    Yes — it is a framework-generated persistence abstraction. Custom ports are optional when you need stronger domain isolation.
    3AdvancedQuestionWhen introduce a hexagonal adapter?+

    Answer

    When you must keep Jakarta/Hibernate out of the domain, support multiple persistence mechanisms, or heavily fake persistence in unit tests.

    Hands-on exercise

    Lab. Refactor an Orders service to depend on a narrow OrderRepository port. Provide a JPA adapter and an in-memory fake. Run the same place-order test against both.

    Summary

    The repository pattern completes the persistence story for Orders — interfaces for intent, JPA behind the curtain. Next modules build services and architecture on this foundation.

    Ready to mark this lesson complete?Track your journey across the entire course.