Spring Data JPA: custom repositories, Specifications and Query by Example

Query methods and @Query cover fixed queries. Search screens with optional filters, shared helper methods and changes to built-in behaviour need more. Spring Data JPA has a mechanism for each: fragments, a base class, Specifications and Query by Example. This page runs every one of them and the mistake that stops the application at startup.

Contents

How a repository is put together

A Spring Data repository looks like one interface, but the proxy behind it is assembled from several parts. When a method is called, Spring Data finds the part that implements it, in this order:

  1. Custom fragments: classes you write that implement extra interfaces the repository extends. They win over everything else, so a fragment can replace a built-in method such as save.
  2. The base class: SimpleJpaRepository by default, which implements JpaRepository, JpaSpecificationExecutor and QueryByExampleExecutor. You can replace it with a subclass for the whole application.
  3. Query methods: methods derived from their names or annotated with @Query, as on the Spring Data JPA page.

Each extension point solves a different problem:

Ways to extend a Spring Data JPA repository
MechanismSinceBest for
Custom fragment (...Impl class)Spring Data 2.0 in its current formOne repository needs code: Criteria API, native SQL, stored procedures
Generic fragment overriding a built-in methodSpring Data 2.0Changing save or delete for some repositories
repositoryBaseClassSpring Data 1.xA helper method on every repository
SpecificationSpring Data JPA 1.0Search with optional filters, built from reusable conditions
PredicateSpecification, UpdateSpecificationSpring Data JPA 4.0Conditions shared by queries, updates and deletes
Query by ExampleSpring Data 1.12Simple search forms: filter by the fields that are filled in
Fluent query (findBy(spec, query -> ...))Spring Data 2.6Projections, sorting and limits on a Specification or Example

The examples use Spring Boot 4.1 with Spring Data JPA 4.1 and Hibernate 7.4 on H2. Most print the SQL Hibernate sends, logged after the test data is inserted.

A custom fragment

A search with two optional filters is awkward as a query method, because every combination of filters needs its own method name. A fragment builds the query in code instead. It has two parts: an interface with the new method, and a class with the same name plus Impl. The repository extends the interface:

Java
package custom.fragment;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class CustomFragment {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CustomFragment.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            BookRepository books = context.getBean(BookRepository.class);
            System.out.println("Implementation behind the proxy: "
                    + AopUtils.getTargetClass(books).getSimpleName());
            books.saveAll(List.of(
                    new Book("Dune", "Herbert", 1965),
                    new Book("Emma", "Austen", 1815),
                    new Book("Persuasion", "Austen", 1817)));
            LoggingSystem.get(CustomFragment.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);

            System.out.println("search(\"Austen\", null)  -> " + books.search("Austen", null));
            System.out.println("search(null, 1900)      -> " + books.search(null, 1900));
            System.out.println("search(null, null)      -> " + books.search(null, null));
            System.out.println("findByAuthor(\"Herbert\") -> " + books.findByAuthor("Herbert"));
        }
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private int published;

    protected Book() {
    }

    Book(String title, String author, int published) {
        this.title = title;
        this.author = author;
        this.published = published;
    }

    @Override
    public String toString() {
        return title;
    }
}

interface BookSearch {
    List<Book> search(String author, Integer publishedAfter);
}

class BookSearchImpl implements BookSearch {
    private final EntityManager em;

    BookSearchImpl(EntityManager em) {
        this.em = em;
    }

    @Override
    public List<Book> search(String author, Integer publishedAfter) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Book> query = cb.createQuery(Book.class);
        Root<Book> book = query.from(Book.class);
        List<Predicate> where = new ArrayList<>();
        if (author != null) {
            where.add(cb.equal(book.get("author"), author));
        }
        if (publishedAfter != null) {
            where.add(cb.greaterThan(book.get("published"), publishedAfter));
        }
        query.where(where.toArray(Predicate[]::new)).orderBy(cb.asc(book.get("title")));
        return em.createQuery(query).getResultList();
    }
}

interface BookRepository extends JpaRepository<Book, Long>, BookSearch {
    List<Book> findByAuthor(String author);
}
Output
Implementation behind the proxy: SimpleJpaRepository
SQL: select b1_0.id,b1_0.author,b1_0.published,b1_0.title from book b1_0 where b1_0.author=? order by b1_0.title
search("Austen", null)  -> [Emma, Persuasion]
SQL: select b1_0.id,b1_0.author,b1_0.published,b1_0.title from book b1_0 where b1_0.published>? order by b1_0.title
search(null, 1900)      -> [Dune]
SQL: select b1_0.id,b1_0.author,b1_0.published,b1_0.title from book b1_0 order by b1_0.title
search(null, null)      -> [Dune, Emma, Persuasion]
SQL: select b1_0.id,b1_0.author,b1_0.published,b1_0.title from book b1_0 where b1_0.author=?
findByAuthor("Herbert") -> [Dune]
SQL: drop table if exists book cascade 
SQL: drop sequence if exists book_seq
  • search("Austen", null) produced only where author=?, and search(null, 1900) only where published>?. With both filters null, the query had no where clause at all. One method handled every combination.
  • findByAuthor, a derived query on the same repository, still works. The proxy sent search to BookSearchImpl and everything else to its usual implementation.
  • The target class behind the proxy is still SimpleJpaRepository; the fragment is an extra part, not a replacement.

Spring Data finds BookSearchImpl by name: it looks for a class called after the fragment interface with the postfix Impl, in the packages it scans for repositories. The class becomes a Spring bean, so its constructor can take the EntityManager, a JdbcTemplate or any other bean. The postfix can be changed with @EnableJpaRepositories(repositoryImplementationPostfix = ...).

The naming mistake that stops startup

Because the implementation is found by name, a class with any other name is not found. Spring Data then treats the fragment's method as a query method and tries to derive a query from its name. This program names its class BookStatsImplementation instead of BookStatsImpl:

Java
package custom.naming;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class FragmentNaming {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FragmentNaming.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try {
            app.run(args).close();
            System.out.println("started");
        } catch (RuntimeException e) {
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            System.out.println("Startup failed: " + cause.getClass().getSimpleName());
            System.out.println(cause.getMessage());
        }
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
}

interface BookStats {
    List<String> longestTitles(int count);
}

class BookStatsImplementation implements BookStats {
    @Override
    public List<String> longestTitles(int count) {
        return List.of();
    }
}

interface BookRepository extends JpaRepository<Book, Long>, BookStats {
}
Output
Startup failed: PropertyReferenceException
No property 'longestTitles' found for type 'Book'

The error does not mention the class at all. Spring Data read longestTitles as a derived query, found no property of that name on Book, and failed with PropertyReferenceException. When a custom method produces a "No property ... found" error at startup, check the Impl class's name and package first. Renaming it to BookStatsImpl fixes it.

Overriding a built-in method

A fragment method with the same signature as a built-in one replaces it, because fragments come first. A generic fragment can do that for several repositories at once. Here a save override trims and lower-cases user emails and tag names before storing them:

Java
package custom.override;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Locale;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

@SpringBootApplication
public class OverrideSave {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(OverrideSave.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            UserRepository users = context.getBean(UserRepository.class);
            TagRepository tags = context.getBean(TagRepository.class);

            users.save(new User("  Ann@Example.COM "));
            tags.save(new Tag(" Java "));
            System.out.println("Users: " + users.findAll());
            System.out.println("Tags : " + tags.findAll());
            System.out.println("Count still comes from SimpleJpaRepository: " + users.count());
        }
    }
}

interface Normalized {
    void normalize();
}

@Entity(name = "AppUser")
class User implements Normalized {
    @Id
    @GeneratedValue
    private Long id;
    private String email;

    protected User() {
    }

    User(String email) {
        this.email = email;
    }

    @Override
    public void normalize() {
        email = email.strip().toLowerCase(Locale.ROOT);
    }

    @Override
    public String toString() {
        return "[" + email + "]";
    }
}

@Entity
class Tag implements Normalized {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    protected Tag() {
    }

    Tag(String name) {
        this.name = name;
    }

    @Override
    public void normalize() {
        name = name.strip().toLowerCase(Locale.ROOT);
    }

    @Override
    public String toString() {
        return "[" + name + "]";
    }
}

interface NormalizingSave<T> {
    <S extends T> S save(S entity);
}

class NormalizingSaveImpl<T> implements NormalizingSave<T> {
    private final EntityManager em;

    NormalizingSaveImpl(EntityManager em) {
        this.em = em;
    }

    @Override
    @Transactional
    public <S extends T> S save(S entity) {
        System.out.println("  NormalizingSaveImpl.save(" + entity + ")");
        if (entity instanceof Normalized normalized) {
            normalized.normalize();
        }
        em.persist(entity);
        return entity;
    }
}

interface UserRepository extends JpaRepository<User, Long>, NormalizingSave<User> {
}

interface TagRepository extends JpaRepository<Tag, Long>, NormalizingSave<Tag> {
}
Output
NormalizingSaveImpl.save([  Ann@Example.COM ])
  NormalizingSaveImpl.save([ Java ])
Users: [[ann@example.com]]
Tags : [[java]]
Count still comes from SimpleJpaRepository: 1
  • Both users.save and tags.save went to NormalizingSaveImpl, as the two log lines show, because both repositories extend NormalizingSave.
  • The stored values are ann@example.com and java: the override ran before the insert.
  • count() and findAll() are not part of the fragment, so they still came from SimpleJpaRepository.

The fragment's type parameter must be unbounded, NormalizingSave<T>. With <T extends Normalized> the code does not compile: javac reports that the call to save is ambiguous between the fragment and CrudRepository. The override is also responsible for everything the original did. This one always calls persist, so it suits only new entities; a complete version would check whether the entity is new and call merge otherwise.

A base class for every repository

When every repository should have the same extra method, a fragment would have to be added to each one. Replacing the base class adds it everywhere. The new method here, getOrThrow, loads by id or throws an exception naming the entity:

Java
package custom.base;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Map;
import java.util.NoSuchElementException;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

@SpringBootApplication
@EnableJpaRepositories(repositoryBaseClass = BaseRepositoryImpl.class)
public class BaseRepositoryClass {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BaseRepositoryClass.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            CityRepository cities = context.getBean(CityRepository.class);
            CountryRepository countries = context.getBean(CountryRepository.class);
            System.out.println("Implementation: "
                    + AopUtils.getTargetClass(cities).getSimpleName());

            Long paris = cities.save(new City("Paris")).getId();
            countries.save(new Country("France"));
            System.out.println("getOrThrow(paris) = " + cities.getOrThrow(paris));
            try {
                countries.getOrThrow(42L);
            } catch (NoSuchElementException e) {
                System.out.println("getOrThrow(42)    = " + e.getMessage());
            }
        }
    }
}

@NoRepositoryBean
interface BaseRepository<T, ID> extends JpaRepository<T, ID> {
    T getOrThrow(ID id);
}

class BaseRepositoryImpl<T, ID> extends SimpleJpaRepository<T, ID>
        implements BaseRepository<T, ID> {

    private final JpaEntityInformation<T, ?> info;

    BaseRepositoryImpl(JpaEntityInformation<T, ?> info, EntityManager em) {
        super(info, em);
        this.info = info;
    }

    @Override
    public T getOrThrow(ID id) {
        return findById(id).orElseThrow(() -> new NoSuchElementException(
                info.getEntityName() + " " + id + " not found"));
    }
}

@Entity
class City {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    protected City() {
    }

    City(String name) {
        this.name = name;
    }

    Long getId() {
        return id;
    }

    @Override
    public String toString() {
        return "City " + name;
    }
}

@Entity
class Country {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    protected Country() {
    }

    Country(String name) {
        this.name = name;
    }
}

interface CityRepository extends BaseRepository<City, Long> {
}

interface CountryRepository extends BaseRepository<Country, Long> {
}
Output
Implementation: BaseRepositoryImpl
getOrThrow(paris) = City Paris
getOrThrow(42)    = Country 42 not found
  • The target class behind the proxy is now BaseRepositoryImpl, set by @EnableJpaRepositories(repositoryBaseClass = ...).
  • getOrThrow(42) on the country repository produced "Country 42 not found". The entity name comes from JpaEntityInformation, which Spring Data passes to the constructor, so one class serves every entity type.
  • BaseRepository is annotated @NoRepositoryBean. Without it, Spring Data would try to create a repository for the interface itself and fail, because it has no concrete entity type.

The base class must extend SimpleJpaRepository and keep its two-argument constructor. Adding @EnableJpaRepositories turns off Spring Boot's own repository scanning, so put it on the application class or name the packages to scan.

Specifications: building queries from conditions

A Specification is one condition of a JPA Criteria query, written as a lambda. Small conditions combine with and, or and not, so a search screen can add only the filters the user filled in. The repository gets the methods by extending JpaSpecificationExecutor. Four products, two of them out of stock, give the filters something to separate:

Java
package custom.spec;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.PredicateSpecification;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.UpdateSpecification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

@SpringBootApplication
public class Specifications {

    static PredicateSpecification<Product> inCategory(String category) {
        return (from, cb) -> cb.equal(from.get("category"), category);
    }

    static PredicateSpecification<Product> cheaperThan(String price) {
        return (from, cb) -> cb.lessThan(from.get("price"), new BigDecimal(price));
    }

    static PredicateSpecification<Product> inStock() {
        return (from, cb) -> cb.greaterThan(from.get("stock"), 0);
    }

    static Specification<Product> search(String category, String maxPrice, boolean stockOnly) {
        Specification<Product> spec = Specification.unrestricted();
        if (category != null) {
            spec = spec.and(inCategory(category));
        }
        if (maxPrice != null) {
            spec = spec.and(cheaperThan(maxPrice));
        }
        if (stockOnly) {
            spec = spec.and(inStock());
        }
        return spec;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Specifications.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            ProductRepository products = context.getBean(ProductRepository.class);
            products.saveAll(List.of(
                    new Product("Desk", "furniture", "199.00", 4),
                    new Product("Chair", "furniture", "89.50", 0),
                    new Product("Lamp", "lighting", "24.99", 12),
                    new Product("Bulb", "lighting", "3.50", 0)));
            LoggingSystem.get(Specifications.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
            Sort byName = Sort.by("name");

            System.out.println("-- furniture under 100");
            System.out.println(products.findAll(search("furniture", "100", false), byName));
            System.out.println("-- anything in stock");
            System.out.println(products.findAll(search(null, null, true), byName));
            System.out.println("-- no filters");
            System.out.println(products.findAll(search(null, null, false), byName));
            System.out.println("-- lighting OR in stock, counted");
            System.out.println(products.count(inCategory("lighting").or(inStock())));
            System.out.println("-- restock everything that is out of stock");
            long updated = products.update(UpdateSpecification.<Product>update(
                    (root, update, cb) -> update.set("stock", 10))
                    .where((from, cb) -> cb.equal(from.get("stock"), 0)));
            System.out.println(updated + " rows updated");
            System.out.println("-- fluent query: cheapest in-stock product, name only");
            System.out.println(products.findBy(inStock(), query -> query
                    .as(ProductName.class)
                    .sortBy(Sort.by("price"))
                    .first())
                    .map(ProductName::getName));
        }
    }
}

@Entity
class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String category;
    private BigDecimal price;
    private int stock;

    protected Product() {
    }

    Product(String name, String category, String price, int stock) {
        this.name = name;
        this.category = category;
        this.price = new BigDecimal(price);
        this.stock = stock;
    }

    @Override
    public String toString() {
        return name;
    }
}

interface ProductName {
    String getName();
}

interface ProductRepository extends JpaRepository<Product, Long>,
        JpaSpecificationExecutor<Product> {
}
Output
-- furniture under 100
SQL: select p1_0.id,p1_0.category,p1_0.name,p1_0.price,p1_0.stock from product p1_0 where p1_0.category=? and p1_0.price<? order by p1_0.name
[Chair]
-- anything in stock
SQL: select p1_0.id,p1_0.category,p1_0.name,p1_0.price,p1_0.stock from product p1_0 where p1_0.stock>? order by p1_0.name
[Desk, Lamp]
-- no filters
SQL: select p1_0.id,p1_0.category,p1_0.name,p1_0.price,p1_0.stock from product p1_0 order by p1_0.name
[Bulb, Chair, Desk, Lamp]
-- lighting OR in stock, counted
SQL: select count(p1_0.id) from product p1_0 where p1_0.category=? or p1_0.stock>?
3
-- restock everything that is out of stock
SQL: update product p1_0 set stock=? where p1_0.stock=?
2 rows updated
-- fluent query: cheapest in-stock product, name only
SQL: select p1_0.name from product p1_0 where p1_0.stock>? order by p1_0.price fetch first ? rows only
Optional[Bulb]
SQL: drop table if exists product cascade 
SQL: drop sequence if exists product_seq
  • "furniture under 100" combined two conditions into category=? and price<?, and found only the Chair.
  • "anything in stock" used one condition, and "no filters" none at all. Specification.unrestricted() is the starting point that adds no where clause, so the search method needs no special case for an empty form.
  • inCategory("lighting").or(inStock()) was passed straight to count, which ran a count query and found 3.
  • UpdateSpecification turned the same style of condition into one UPDATE statement that changed 2 rows. Like any bulk update, it bypasses loaded entities, versions and callbacks.
  • The fluent query findBy(inStock(), query -> ...) combined a condition with a projection, a sort and first(). Hibernate selected only the name column and one row. After the restock every product was in stock, so the cheapest one is the Bulb.

The conditions here are PredicateSpecification, added in Spring Data JPA 4.0. It receives only a From and the CriteriaBuilder, not the query, so the same condition works in selects, updates and deletes. The older Specification also receives the CriteriaQuery, which a condition needs only for things like subqueries. Property names written as strings, such as "price", are checked only when the query runs. The JPA static metamodel (Product_.price), generated by the Hibernate annotation processor, catches mistakes at compile time.

Query by Example

Query by Example builds the condition from an entity object: every property that is not null becomes part of the where clause. An ExampleMatcher controls how strings are compared and whether conditions are joined with and or or:

Java
package custom.qbe;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class QueryByExample {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(QueryByExample.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            PersonRepository people = context.getBean(PersonRepository.class);
            people.saveAll(List.of(
                    new Person("Ann", "Smith", "London", 34),
                    new Person("Bob", "Smithers", "London", 41),
                    new Person("Cara", "Jones", "Leeds", 34)));
            LoggingSystem.get(QueryByExample.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
            Sort byFirst = Sort.by("firstName");

            Person probe = new Person(null, null, "London", null);
            System.out.println("-- city = London");
            System.out.println(people.findAll(Example.of(probe), byFirst));

            Person prefix = new Person(null, "smith", null, null);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("lastName", GenericPropertyMatchers.startsWith().ignoreCase());
            System.out.println("-- last name starts with 'smith', any case");
            System.out.println(people.findAll(Example.of(prefix, matcher), byFirst));

            Person any = new Person("Cara", null, "London", null);
            System.out.println("-- first name Cara OR city London");
            System.out.println(people.findAll(Example.of(any, ExampleMatcher.matchingAny()),
                    byFirst));
        }
    }
}

@Entity
class Person {
    @Id
    @GeneratedValue
    private Long id;
    private String firstName;
    private String lastName;
    private String city;
    private Integer age;

    protected Person() {
    }

    Person(String firstName, String lastName, String city, Integer age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.city = city;
        this.age = age;
    }

    @Override
    public String toString() {
        return firstName + " " + lastName + " (" + city + ", " + age + ")";
    }
}

interface PersonRepository extends JpaRepository<Person, Long> {
}
Output
-- city = London
SQL: select p1_0.id,p1_0.age,p1_0.city,p1_0.first_name,p1_0.last_name from person p1_0 where p1_0.city=? order by p1_0.first_name
[Ann Smith (London, 34), Bob Smithers (London, 41)]
-- last name starts with 'smith', any case
SQL: select p1_0.id,p1_0.age,p1_0.city,p1_0.first_name,p1_0.last_name from person p1_0 where lower(p1_0.last_name) like ? escape '\' order by p1_0.first_name
[Ann Smith (London, 34), Bob Smithers (London, 41)]
-- first name Cara OR city London
SQL: select p1_0.id,p1_0.age,p1_0.city,p1_0.first_name,p1_0.last_name from person p1_0 where p1_0.city=? or p1_0.first_name=? order by p1_0.first_name
[Ann Smith (London, 34), Bob Smithers (London, 41), Cara Jones (Leeds, 34)]
SQL: drop table if exists person cascade 
SQL: drop sequence if exists person_seq
  • The first probe had only city set, so the query was where city=?, and the null name and age fields were ignored.
  • The matcher for lastName turned "smith" into lower(last_name) like ? with a prefix match, so both Smith and Smithers matched.
  • ExampleMatcher.matchingAny() joined the two set properties with or, adding Cara from Leeds.

Primitive fields are never null, so they always take part: with int age instead of Integer age, every probe would also require age = 0. Use wrapper types or withIgnorePaths("age"). Query by Example handles equality and string matching only; ranges such as "price below 100", and conditions on collections, need Specifications.

Querydsl

Querydsl is a third-party library that generates query classes from entities, such as QBook.book, and lets you write type-safe conditions like book.author.eq("Austen").and(book.published.gt(1900)). A repository that extends QuerydslPredicateExecutor<Book> accepts those conditions in findAll, count and exists, much like JpaSpecificationExecutor accepts Specifications.

The Querydsl example was not run on this page, because the Querydsl jars and its annotation processor are not among the Spring Boot starters used here. It needs the querydsl-jpa dependency and the querydsl-apt processor configured in the build to generate the Q classes. Compared with Specifications, it reads more naturally and is checked at compile time, at the cost of an extra library and a code generation step.

Choosing an extension point

Which mechanism fits which need
NeedUse
A search form with a few optional filtersSpecifications, built from small reusable conditions
A form that only filters by equality or textQuery by Example
Code that one repository needs: native SQL, JDBC, stored proceduresA custom fragment with an Impl class
Different save or delete behaviour for some repositoriesA generic fragment overriding the method
A helper method on every repositoryrepositoryBaseClass with a @NoRepositoryBean interface
Only some columns, or only the first row, of a dynamic queryThe fluent findBy with as, sortBy, first or page
Type-safe dynamic queries, and a code generator is acceptableQuerydsl or the JPA static metamodel with Specifications

Prefer the simplest mechanism that works: a derived query or @Query is easier to read than any of these. For fetching associations and projections in these queries, see Spring Data JPA advanced; for the transactions they run in, see @Transactional.