Sub topic 8
Derived Query Methods
This chapter assumes you can write a Spring Boot application, you know basic SQL, and you have mapped Author and Book entities as in the earlier chapters. It also assumes you have a repository interface extending JpaRepository. You will learn how Spring Data turns a method name into a query, which keywords exist, and which errors show up most often.
What a derived query is
A derived query method is a repository method whose name describes the query. Spring Data parses the name at startup, builds a JPQL query (and from it SQL), and generates the implementation. You write no query text and no method body.
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByTitleContainingIgnoreCase(String text);
}Spring reads findByTitleContainingIgnoreCase and produces roughly select b from Book b where upper(b.title) like upper(?1). The argument is wrapped with % on both sides for you.
Because parsing happens when the application context starts, a misspelled property fails at startup, not on the first call. This is a useful safety net.
How the method name is parsed
A name has two parts, separated by the first By.
- The subject comes before
By. It starts with a verb (find,read,get,query,search,stream,count,exists,delete,remove). Words between the verb andByare ignored, exceptDistinct,First, andTop. SofindAllBooksByTitleandfindByTitlebehave the same. - The predicate comes after
By. It is a list of property conditions joined withAndandOr.
Each predicate part is a property path plus an optional keyword. PublishedYearGreaterThan means property publishedYear, keyword GreaterThan. If you give no keyword, the default is equality.
Common keywords
| Keyword | Example method | Resulting condition |
|---|---|---|
| (none) / `Is` / `Equals` | `findByTitle(String t)` | `title = ?1` |
| `Not` | `findByTitleNot(String t)` | `title <> ?1` |
| `And`, `Or` | `findByTitleAndPublishedYear(...)` | `title = ?1 and publishedYear = ?2` |
| `GreaterThan`, `GreaterThanEqual` | `findByPublishedYearGreaterThanEqual(int y)` | `publishedYear >= ?1` |
| `LessThan`, `LessThanEqual` | `findByPublishedYearLessThan(int y)` | `publishedYear < ?1` |
| `Between` | `findByPublishedYearBetween(int a, int b)` | `publishedYear between ?1 and ?2` |
| `Like`, `NotLike` | `findByTitleLike(String p)` | `title like ?1` (you supply `%`) |
| `StartingWith`, `EndingWith`, `Containing` | `findByTitleStartingWith(String p)` | `title like ?1%` |
| `In`, `NotIn` | `findByPublishedYearIn(Collection<Integer> ys)` | `publishedYear in (?1)` |
| `IsNull`, `IsNotNull` | `findByTitleIsNull()` | `title is null` |
| `True`, `False` | `findByActiveTrue()` | `active = true` |
| `IgnoreCase` | `findByTitleIgnoreCase(String t)` | `upper(title) = upper(?1)` |
The Like keyword does not add wildcards. StartingWith, EndingWith, and Containing do, and they also escape wildcard characters in the argument.
Return types and the subject keywords
The return type decides what the query produces.
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
public interface BookRepository extends JpaRepository<Book, Long> {
Optional<Book> findByTitle(String title);
List<Book> findByPublishedYear(int year);
Stream<Book> streamByPublishedYear(int year);
long countByPublishedYear(int year);
boolean existsByTitle(String title);
long deleteByPublishedYear(int year);
}Optional<Book>or a plainBookexpects at most one row. If the query returns two rows, Spring throwsIncorrectResultSizeDataAccessException. A plainBookreturn value isnullwhen nothing matches.List,Collection, andSethold all rows. An empty result gives an empty collection, nevernull.Streammust be closed, and the call must run inside a transaction. Use try-with-resources.count...Byandexists...Byavoid loading entities.delete...Byloads each matching entity first, then removes them one at a time. This lets lifecycle callbacks and cascades run, but it is slow for large sets. Call it inside a@Transactionalmethod.
Limiting and ordering
First and Top limit the number of rows. A number after them sets the limit; with no number the limit is 1.
import java.util.List;
import java.util.Optional;
public interface BookRepository extends JpaRepository<Book, Long> {
Optional<Book> findFirstByOrderByPublishedYearAsc();
List<Book> findTop3ByPublishedYearGreaterThanOrderByPublishedYearDesc(int year);
List<Book> findDistinctByAuthorName(String name);
}Note that findFirstByOrderBy... has an empty condition between By and OrderBy. That is valid and means "no filter".
Put OrderBy at the end of the name, followed by a property and Asc or Desc. Several sort properties can be chained: OrderByPublishedYearDescTitleAsc. For sorts decided at runtime, add a Sort parameter instead, which the pagination chapter covers.
Traversing associations
You can reach into a related entity with a property path. In findByAuthorName, Spring resolves Author as the property author on Book, then Name as author.name. It generates a join automatically.
List<Book> findByAuthorName(String name);
List<Book> findByAuthor(Author author);
List<Book> findByAuthorId(Long authorId);The second form compares against the foreign key of a given entity. The third uses the id of the association directly.
Ambiguous paths
Spring tries to match the longest property name first, then works backward. If Book had both a property authorName and an association author with a property name, then findByAuthorName would pick authorName. To force the nested path, use an underscore: findByAuthor_Name. The underscore is a deliberate delimiter and is the one place where it is idiomatic in Java method names.
Derived queries do not fetch the association. Calling findByAuthorName joins to filter, but book.getAuthor() still triggers a lazy load afterward, which causes N+1 selects. Add @EntityGraph(attributePaths = "author") to the method to fetch it in the same select, as shown in the earlier repository example.
Parameters
Parameters bind by position, in the order the keywords appear. Between consumes two parameters. IsNull and True consume none. In takes a collection.
List<Book> findByTitleAndPublishedYearBetween(String title, int from, int to);Passing null to a plain equality keyword produces = null, which matches nothing in SQL. Spring Data does convert null to is null for simple equality in many versions, but do not depend on it. Use IsNull explicitly when you need that behavior.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `PropertyReferenceException: No property 'titel' found for type 'Book'` at startup | Typo in the method name, or the property does not exist | Match the field name in the entity, with the correct case |
| `QueryCreationException` mentioning parameters | Parameter count does not match the keywords | Count: `Between` needs two, `IsNull` needs none |
| `IncorrectResultSizeDataAccessException` | Single-result return type but multiple rows matched | Return a `List`, add `First`, or fix the data |
| `LazyInitializationException` after the call | Association read outside a transaction | Use `@EntityGraph` or a `join fetch` query |
| Method name has grown to 100+ characters | Too many conditions for a derived query | Switch to `@Query` |
When to stop using derived queries
Derived names work well for up to about two or three conditions. Beyond that, the name is hard to read and hard to refactor. Use @Query (next chapter) when you need joins with custom conditions, subqueries, aggregation, or when the name stops fitting on a line. A derived query is also a poor choice for dynamic filtering where conditions are optional. For that, use Specification or Querydsl.
Summary of rules
- Names have the form
verb+ optional words +By+ conditions + optionalOrderBy. - Property names in the method must match entity fields exactly, apart from the first letter's case.
- Startup validation catches most mistakes early.
- Derived queries filter by associations but do not fetch them.
Exercise
You have Book with a String title, int publishedYear, and a many-to-one author that has a String name. Write the derived query method signature that returns the two most recently published books by an author whose name is given, sorted newest first. Then say what happens if the database has no matching rows.
Show answer
List<Book> findTop2ByAuthorNameOrderByPublishedYearDesc(String name); The method returns an empty list, not null, because the return type is a collection. If the return type were Optional<Book> with findFirstBy..., the result would be Optional.empty().
Exercise
A teammate writes Book findByTitle(String title); and the application throws IncorrectResultSizeDataAccessException in production. What is the cause, and give two ways to fix it?
Show answer
Two or more rows have the same title, but the return type allows at most one. Fix it by returning List<Book>, or by using findFirstByTitle (optionally with an OrderBy) so the query limits the result to one row. Adding a unique constraint on the column is a third option if titles should be unique.