java 31 lines · 8 steps

Deriving JPA queries from method names in Spring

Spring Data JPA generates real SQL from repository method names, so a naming convention replaces hand-written queries.

Explained by highlit
1package com.example.shop.repository;
2 
3import com.example.shop.domain.Order;
4import com.example.shop.domain.OrderStatus;
5import org.springframework.data.domain.Page;
6import org.springframework.data.domain.Pageable;
7import org.springframework.data.jpa.repository.JpaRepository;
8import org.springframework.stereotype.Repository;
9 
10import java.math.BigDecimal;
11import java.time.Instant;
12import java.util.List;
13import java.util.Optional;
14 
15@Repository
16public interface OrderRepository extends JpaRepository<Order, Long> {
17 
18 List<Order> findByCustomerIdOrderByCreatedAtDesc(Long customerId);
19 
20 Page<Order> findByStatusAndTotalGreaterThanEqual(OrderStatus status, BigDecimal minTotal, Pageable pageable);
21 
22 Optional<Order> findFirstByCustomerIdAndStatusOrderByCreatedAtDesc(Long customerId, OrderStatus status);
23 
24 List<Order> findByStatusInAndCreatedAtBetween(List<OrderStatus> statuses, Instant from, Instant to);
25 
26 boolean existsByReferenceIgnoreCase(String reference);
27 
28 long countByCustomerIdAndStatus(Long customerId, OrderStatus status);
29 
30 List<Order> findTop10ByCustomerCountryAndStatusNotOrderByTotalDesc(String country, OrderStatus excludedStatus);
31}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Method names in a Spring Data repository are parsed into queries, so structure beats boilerplate.
  2. 2Return types shape behavior: Optional guards absence, Page adds paging metadata, List returns everything.
  3. 3Keywords like In, Between, GreaterThanEqual, and Top10 express filtering, ranges, and limits without any SQL.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deriving JPA queries from method names in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code