पाठ 12 / 25

Repositories and Derived Queries

Interfaces, no implementation.

JpaRepository and method-name queries

Extending JpaRepository<Product, Long> gives CRUD, paging and sorting methods without writing an implementation. Derived queries turn method names into queries: findByPriceLessThanOrderByPriceAsc(max) filters and sorts. For complex queries use @Query with JPQL or native SQL, or projections that select only needed columns. Watch for the N+1 query problem when loading related entities lazily in loops; use fetch joins or entity graphs.

A repository with a derived query

This file is from a demo "shop" service generated by start.spring.io for Spring Boot 4.1.1 and Java 21 (Temurin 21.0.12), built with Maven 3.9.16; the project compiled and its tests passed. Spring Data generates the implementation and the query from the method name.

package com.example.shop;

import java.math.BigDecimal;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
    // Spring Data derives the query from the method name
    List<Product> findByPriceLessThanOrderByPriceAsc(BigDecimal max);
}

Log SQL while developing

Temporarily enable SQL logging to see the queries Hibernate generates and catch N+1 problems early.

त्वरित जाँच: How does Spring Data implement findByPriceLessThan?

  • You must write the SQL in a separate class
  • It derives the query from the method name
  • It loads all rows and filters in Java always
  • It calls an external API
Answer

It derives the query from the method name — Naming conventions become queries.