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:
- 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 - The base class:
by default, which implementsSimpleJpaRepository ,JpaRepository andJpaSpecificationExecutor . You can replace it with a subclass for the whole application.QueryByExampleExecutor - Query methods: methods derived from their names or annotated with
, as on the@QuerySpring Data JPA page.
Each extension point solves a different problem:
| Mechanism | Since | Best for |
|---|---|---|
Custom fragment (...Impl | Spring Data 2.0 in its current form | One repository needs code: Criteria API, native SQL, stored procedures |
| Generic fragment overriding a built-in method | Spring Data 2.0 | Changing savedelete |
repositoryBaseClass | Spring Data 1.x | A helper method on every repository |
Specification | Spring Data JPA 1.0 | Search with optional filters, built from reusable conditions |
PredicateSpecificationUpdateSpecification | Spring Data JPA 4.0 | Conditions shared by queries, updates and deletes |
| Query by Example | Spring Data 1.12 | Simple search forms: filter by the fields that are filled in |
Fluent query (findBy(spec, query -> ...) | Spring Data 2.6 | Projections, 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
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);
}
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
produced onlysearch("Austen", null) , andwhere author=? onlysearch(null, 1900) . With both filterswhere published>? , the query had nonull clause at all. One method handled every combination.where , a derived query on the same repository, still works. The proxy sentfindByAuthor tosearch and everything else to its usual implementation.BookSearchImpl- The target class behind the proxy is still
; the fragment is an extra part, not a replacement.SimpleJpaRepository
Spring Data finds BookSearchImplImplEntityManagerJdbcTemplate@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 BookStatsImplementationBookStatsImpl
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 {
}
Startup failed: PropertyReferenceException
No property 'longestTitles' found for type 'Book'
The error does not mention the class at all. Spring Data read longestTitlesBookPropertyReferenceExceptionImplBookStatsImpl
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
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> {
}
NormalizingSaveImpl.save([ Ann@Example.COM ])
NormalizingSaveImpl.save([ Java ])
Users: [[ann@example.com]]
Tags : [[java]]
Count still comes from SimpleJpaRepository: 1
- Both
andusers.save went totags.save , as the two log lines show, because both repositories extendNormalizingSaveImpl .NormalizingSave - The stored values are
andann@example.com : the override ran before the insert.java andcount() are not part of the fragment, so they still came fromfindAll() .SimpleJpaRepository
The fragment's type parameter must be unbounded, NormalizingSave<T><T extends Normalized>saveCrudRepositorypersistmerge
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
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> {
}
Implementation: BaseRepositoryImpl
getOrThrow(paris) = City Paris
getOrThrow(42) = Country 42 not found
- The target class behind the proxy is now
, set byBaseRepositoryImpl .@EnableJpaRepositories(repositoryBaseClass = ...) on the country repository produced "Country 42 not found". The entity name comes fromgetOrThrow(42) , which Spring Data passes to the constructor, so one class serves every entity type.JpaEntityInformation is annotatedBaseRepository . Without it, Spring Data would try to create a repository for the interface itself and fail, because it has no concrete entity type.@NoRepositoryBean
The base class must extend SimpleJpaRepository@EnableJpaRepositories
Specifications: building queries from conditions
A SpecificationandornotJpaSpecificationExecutor
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> {
}
-- 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
, and found only the Chair.category=? and price<? - "anything in stock" used one condition, and "no filters" none at all.
is the starting point that adds noSpecification.unrestricted() clause, so thewhere method needs no special case for an empty form.search was passed straight toinCategory("lighting").or(inStock()) , which ran acount query and found 3.count turned the same style of condition into oneUpdateSpecification statement that changed 2 rows. Like any bulk update, it bypasses loaded entities, versions and callbacks.UPDATE- The fluent query
combined a condition with a projection, a sort andfindBy(inStock(), query -> ...) . Hibernate selected only thefirst() column and one row. After the restock every product was in stock, so the cheapest one is the Bulb.name
The conditions here are PredicateSpecificationFromCriteriaBuilderSpecificationCriteriaQuery"price"Product_.price
Query by Example
Query by Example builds the condition from an entity object: every property that is not nullwhereExampleMatcherandor
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> {
}
-- 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
set, so the query wascity , and thewhere city=? name and age fields were ignored.null - The matcher for
turned "smith" intolastName with a prefix match, so both Smith and Smithers matched.lower(last_name) like ? joined the two set properties withExampleMatcher.matchingAny() , adding Cara from Leeds.or
Primitive fields are never nullint ageInteger ageage = 0withIgnorePaths("age")
Querydsl
Querydsl is a third-party library that generates query classes from entities, such as QBook.bookbook.author.eq("Austen").and(book.published.gt(1900))QuerydslPredicateExecutor<Book>findAllcountexistsJpaSpecificationExecutor
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-jpaquerydsl-aptQ
Choosing an extension point
| Need | Use |
|---|---|
| A search form with a few optional filters | Specifications, built from small reusable conditions |
| A form that only filters by equality or text | Query by Example |
| Code that one repository needs: native SQL, JDBC, stored procedures | A custom fragment with an Impl |
Different savedelete | A generic fragment overriding the method |
| A helper method on every repository | repositoryBaseClass@NoRepositoryBean |
| Only some columns, or only the first row, of a dynamic query | The fluent findByassortByfirstpage |
| Type-safe dynamic queries, and a code generator is acceptable | Querydsl or the JPA static metamodel with Specifications |
Prefer the simplest mechanism that works: a derived query or @Query