Sub topic 8
Derived query methods
This chapter assumes you know the Book and Author entities, can write a repository interface that extends JpaRepository, and can read basic SQL where clauses.
What a derived query is
A derived query method is a repository method whose name describes a query. At startup, Spring Data parses the name, builds a JPQL query from it, and generates the implementation. You write no query text and no method body.
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByTitleContainingIgnoreCase(String text);
List<Book> findByPublishedYearBetweenOrderByTitleAsc(int from, int to);
Optional<Book> findFirstByOrderByPublishedYearDesc();
boolean existsByTitle(String title);
long countByPublishedYearLessThan(int year);
List<Book> findByAuthorName(String name);
}How a name is parsed
Spring splits the name into a subject and a predicate. The subject is the prefix before By, such as find, exists, count or delete. The predicate is everything after By.
Common keywords
| Keyword | Meaning |
|---|---|
| `And`, `Or` | Combine conditions |
| `Between`, `LessThan`, `GreaterThanEqual` | Comparisons |
| `Containing`, `StartingWith`, `EndingWith` | Pattern match, wildcards added for you |
| `IgnoreCase` | Case-insensitive comparison |
| `In`, `IsNull`, `True` | Collection, null and boolean checks |
| `OrderBy...Asc/Desc` | Fixed sort order |
| `First`, `Top3`, `Distinct` | Limit or deduplicate results |
Parameters bind to conditions in the order they appear in the name. Between takes two parameters.
Navigating associations
findByAuthorName follows Book.author and then Author.name, so Spring creates a join. If a name could be read in more than one way, for example an authorName field next to an author association, Spring picks the field. Use an underscore to force the path: findByAuthor_Name.
Return types
List<T>,Stream<T>: any number of rows. Close aStreamafter use.Optional<T>orT: at most one row.Page<T>orSlice<T>: add aPageableparameter, covered in the pagination chapter.boolean,long: forexistsandcount.
Common errors
- A misspelled property, such as
findByTitel, throwsPropertyReferenceException. The application fails at startup, not at the first call. - Fewer parameters than conditions causes an error when the repository is created.
- A single-result method that matches several rows throws
IncorrectResultSizeDataAccessException. UseFirstor return aList. Likedoes not add wildcards. You must pass"%war%"yourself.Containingadds them.- Long names such as
findByAuthorNameAndPublishedYearGreaterThanEqualAndTitleContainingare hard to read. When a name grows past three conditions, switch to@Query.
Exercise
Write a derived query method on BookRepository that returns the three most recently published books by an author with a given name. Which two parts of the method name limit and sort the result?
Show answer
List<Book> findTop3ByAuthorNameOrderByPublishedYearDesc(String name); Top3 limits the result to three rows, and OrderByPublishedYearDesc sorts newest first before the limit is applied.