Spring Data Query Methods: Derived Queries, @Query and Projections
Fantasy books after 2020, newest first, asked four ways: a plain EntityManager query, a derived method name, @Query with named parameters, and a two-column projection. Plus the startup error one missing letter causes.
What you will learn
- Read a derived query method name piece by piece and predict its SQL
- Switch to @Query with named parameters when the name gets too long
- Load only the columns a page needs with an interface projection
- Recognise the startup error a typo in a method name causes
Before you start
- JPA Entity Mapping: Ids, Enums and Dates
- Spring Boot Repository and Service Layer
A library app holds 8 books by 4 authors. The question: fantasy books published after 2020, newest first. Three books match. You'll ask it four ways and watch the SQL each time, because the SQL log is the proof.
1 | The Silver Orchard | Fantasy | 2021-03-14 | Eleanor Marsh | UK
2 | Dragon Tide | Fantasy | 2019-06-02 | Eleanor Marsh | UK
3 | The Last Lantern | Fantasy | 2023-09-21 | Eleanor Marsh | UK
4 | Crown of Embers | Fantasy | 2022-01-30 | Daniel Hart | US
5 | Orbit Nine | Sci-Fi | 2024-05-10 | Daniel Hart | US
6 | Cold Signal | Sci-Fi | 2018-11-08 | Grace Whitfield | Canada
7 | The Quiet Witness | Mystery | 2020-11-05 | Grace Whitfield | Canada
8 | Midnight on Harbor Street | Mystery | 2022-08-19 | Oliver Banks | Australia
The plain way: an EntityManager query
@Component
public class PlainBookFinder {
@PersistenceContext
private EntityManager em;
public List<Book> genreAfter(String genre, LocalDate date) {
return em.createQuery(
"select b from Book b where b.genre = :genre "
+ "and b.publishedOn > :date "
+ "order by b.publishedOn desc", Book.class)
.setParameter("genre", genre)
.setParameter("date", date)
.getResultList();
}
}
It works. But the query is a text string, so a typo only shows up when that line runs. And every new question needs another string, another method, and two more setParameter calls.
The name is the query
With Spring Data, you write one interface method and no body:
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByGenreAndPublishedOnAfterOrderByPublishedOnDesc(
String genre, LocalDate date);
}
The name is made of five small pieces, and each piece is part of the query:
A runner calls it with "Fantasy" and LocalDate.of(2020, 12, 31). With show-sql: true, the Run window shows the SQL Spring wrote:
Hibernate: select
b1_0.id,b1_0.author_id,b1_0.genre,b1_0.published_on,b1_0.title from book
b1_0 where b1_0.genre=? and b1_0.published_on>? order by
b1_0.published_on desc
The Last Lantern (2023-09-21)
Crown of Embers (2022-01-30)
The Silver Orchard (2021-03-14)
It's the same SQL as the plain way, and nobody typed it. There's no class behind the interface either. Spring creates one when the app starts, and save, findById and friends come from JpaRepository.
When the name reads like a paragraph, use @Query
Now the question grows: only authors from the UK. The derived name still works, but look at it:
List<Book> findByGenreAndAuthorCountryAndPublishedOnAfterOrderByPublishedOnDesc(
String genre, String country, LocalDate date);
AuthorCountry walks from Book into its author and reads country. Correct, and painful to read. Write the query yourself instead:
@Query("select b from Book b where b.genre = :genre "
+ "and b.author.country = :country "
+ "and b.publishedOn > :date order by b.publishedOn desc")
List<Book> recentFrom(
@Param("genre") String genre,
@Param("country") String country,
@Param("date") LocalDate date);
Both return the same two books: The Last Lantern (2023-09-21) and The Silver Orchard (2021-03-14). So the choice is only about reading. If the name reads like a sentence, keep it. If it reads like a paragraph, write the @Query. The query is JPQL: it talks about the Book class and its fields, not the table.
Projections: read only what the page shows
The list page needs two things: the title and the author's name. Loading whole Book objects reads five columns and builds an Author for each. An interface with two getters is enough:
public interface BookSummary {
String getTitle();
String getAuthorName();
}
@Query("select b.title as title, b.author.name as authorName "
+ "from Book b where b.genre = :genre "
+ "and b.publishedOn > :date order by b.publishedOn desc")
List<BookSummary> summaries(
@Param("genre") String genre,
@Param("date") LocalDate date);
Hibernate: select b1_0.title,a1_0.name from book b1_0 join author a1_0 on
a1_0.id=b1_0.author_id where b1_0.genre=? and b1_0.published_on>? order
by b1_0.published_on desc
The Last Lantern by Eleanor Marsh
Crown of Embers by Daniel Hart
The Silver Orchard by Eleanor Marsh
Two columns instead of five, and no Author object is built. The aliases (as title, as authorName) must match the getter names, which is how Spring knows which value goes where.
Break it: one missing letter
Write After as Aftr:
List<Book> findByGenreAndPublishedOnAftr(String genre, LocalDate date);
ERROR o.s.boot.SpringApplication : Application run failed
Caused by: org.springframework.data.repository.query.QueryCreationException:
Cannot create query for method
[BookRepository.findByGenreAndPublishedOnAftr(java.lang.String,java.
time.LocalDate)]; No property 'aftr' found for type 'LocalDate';
Traversed path: Book.publishedOn
Spring found publishedOn on Book, then looked for a property called aftr inside LocalDate and found nothing. The app doesn't even start. That's a good thing: the typo is caught on day one, on your machine, and never reaches a user. Compare that with the string in PlainBookFinder, which fails only when someone calls it.
Common mistakes
- Parameters in the wrong order. A derived query fills the question marks in the order of the name: genre first, then the date.
- Field names, not column names. The name uses
PublishedOn(the Java field), neverpublished_on. - Projection aliases that don't match.
getAuthorName()needsas authorNamein the query. - Forty-word method names. They work, but nobody can review them. Switch to
@Query.
Recap
| Way | Use it when | Checked |
|---|---|---|
Plain EntityManager | rarely, for one-off queries | when it runs |
| Derived method name | the name reads like a short sentence | at startup |
@Query with @Param | the name would read like a paragraph | at startup |
| Interface projection | the page needs only a few columns | at startup |
Try it yourself
Add long countByGenre(String genre) to BookRepository and print countByGenre("Mystery"). Predict the SQL before you run it, then check the log. (From the list above, the answer should be 2.)
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
