Spring Data JPA
Spring Data JPA turns a repository interface into a runtime implementation.
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/totalCentswithout full graphs.
Step-by-step explanation
- Create
OrderRepository extends JpaRepository<Order, Long>. - Add a derived finder for user + status with sort.
- Add a paged finder and a DTO projection query.
- Call the repository only from
OrderService; verify with an integration test.
Informative example
Orders repository with derived query, page, and projection.
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
findByIdwithout ownership checks. - Parameterized
@Querybinds — 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
Pageableon every list-shaped API from day one.
Common mistakes
- Injecting
OrderRepositoryinto controllers. - Calling
findAll()on production data. - Writing 12-part derived method names instead of readable
@QueryJPQL.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat does extending JpaRepository give you?+
Answer
2IntermediateQuestionWhen should you switch from a derived query to @Query?+
Answer
3IntermediateQuestionWhy avoid findAll in Orders APIs?+
Answer
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.