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

    Spring Data JPA

    Spring Data JPA turns a repository interface into a runtime implementation.

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

    Introduction

    Spring Data JPA turns a repository interface into a runtime implementation. You extend JpaRepository<Order, Long>; Boot supplies save, findById, paging helpers, and more — no boilerplate DAO class.

    Derived query methods read like English: findByUserIdAndStatusOrderByCreatedAtDesc. When names get awkward, switch to @Query JPQL. Always return pages or projections for list endpoints — never unbounded findAll() in production Orders.

    Repositories sit behind OrderService. Controllers never inject them. Transactions typically start on the service; repository methods join the existing persistence context.

    Spring Boot 3 uses Jakarta persistence types under the hood. Your entity classes import jakarta.persistence.*, not javax.persistence.

    Purpose of this lesson

    Declare Orders repositories with Spring Data JPA — derived queries, paging, projections — while keeping services as the transactional boundary.

    Understanding the topic

    Interfaces declare intent; Spring generates the implementation.

    • JpaRepository: CRUD + paging + flush helpers for Order.
    • Derived queries: method names become SQL predicates.
    • @Query: explicit JPQL when names exceed ~3 conditions.
    • Page / Slice: mandatory for list APIs.
    • Projections: load id/status/totalCents without full graphs.

    Step-by-step explanation

    1. Create OrderRepository extends JpaRepository<Order, Long>.
    2. Add a derived finder for user + status with sort.
    3. Add a paged finder and a DTO projection query.
    4. Call the repository only from OrderService; verify with an integration test.

    Informative example

    Orders repository with derived query, page, and projection.

    java
    public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByUserIdAndStatusOrderByCreatedAtDesc(
    Long userId, OrderStatus status);
    Page<Order> findByStatus(OrderStatus status, Pageable pageable);
    @Query("""
    select new com.acme.orders.OrderSummary(o.id, o.status, o.totalCents)
    from Order o where o.userId = :uid
    """)
    List<OrderSummary> summariesFor(@Param("uid") Long uid);
    @Query("select count(o) from Order o where o.status = ?1")
    long countByStatus(OrderStatus status);
    }
    // Service usage
    @Transactional(readOnly = true)
    public Page<OrderView> list(OrderStatus status, Pageable pageable) {
    return orders.findByStatus(status, pageable).map(OrderView::from);
    }

    Output

    Page 0 of PENDING orders → content size 20, totalElements 134

    Real-world use

    The TechLearningPRO account page lists a learner's recent orders. The service calls findByUserIdAndStatusOrderByCreatedAtDesc or a paged variant — never a full table scan — so mobile clients stay fast as the ledger grows.

    Security implications

    Repository methods are not authorization.

    • Always filter by the authenticated user id in the service for 'my orders'.
    • Do not expose arbitrary findById without ownership checks.
    • Parameterized @Query binds — never concatenate user input into JPQL strings.

    Best practices

    • Prefer projections for read-heavy summaries.
    • Keep repository methods intention-revealing; push orchestration to the service.
    • Use Pageable on every list-shaped API from day one.

    Common mistakes

    • Injecting OrderRepository into controllers.
    • Calling findAll() on production data.
    • Writing 12-part derived method names instead of readable @Query JPQL.

    Advanced interview questions

    Interview Prep

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

    3 questions
    1BeginnerQuestionWhat does extending JpaRepository give you?+

    Answer

    A Spring-generated implementation with standard CRUD, existence checks, and paging operations for the entity/id type pair.
    2IntermediateQuestionWhen should you switch from a derived query to @Query?+

    Answer

    When the method name becomes hard to read, needs joins/fetch, or requires a constructor expression projection.
    3IntermediateQuestionWhy avoid findAll in Orders APIs?+

    Answer

    Unbounded loads grow with table size, spike latency and memory, and can take down the pool under load.

    Hands-on exercise

    Lab. Implement OrderRepository as above against Postgres. From a test or shell, insert three orders and page findByStatus(PENDING, PageRequest.of(0, 2)). Confirm total elements and page size.

    Summary

    Spring Data JPA is the Orders persistence façade. Next you look under the hood at Hibernate — the JPA provider Boot ships by default.

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