liveBook · Manning

Custom query method

As explained in Spring in Action, Sixth Edition

A custom query method is a repository method whose query is explicitly specified rather than derived entirely from the method name.

A custom query method explicitly specifies its query instead of relying entirely on Spring Data’s method-name convention. Name the method freely, then add @Query to define what runs when it is called. section 3.3.4

Find orders delivered in Seattle

This repository method uses @Query to return every order whose delivery city is Seattle, even though the method name does not describe the query structure. section 3.3.4

Choose a custom query method when:

  • A derived method name would become unwieldy for a complex query. section 3.3.4
  • Spring Data JDBC requires an explicit query because it cannot infer one from method-name metadata. section 3.3.4
  • The query language must match the repository technology: JPA queries for JPA and SQL for Spring Data JDBC. section 3.3.4
@Query("Order o where o.deliveryCity='Seattle'")
List<TacoOrder> readOrdersDeliveredInSeattle();

Inspect the complete annotated repository method for the Seattle delivery query. section 3.3.4

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains naming limits, @Query usage, and JPA-versus-SQL differences without detailing query execution internals.
Examples
Shows a TacoOrder repository method returning orders delivered in Seattle.
What it assumes
Assumes repository methods and naming conventions, while distinguishing JPA query syntax from Spring Data JDBC SQL.
What you can do after
Apply it via @Query to define repository queries that method-name conventions cannot express conveniently.
How it connects
Connects repository method naming with @Query, JPA queries, Spring Data JDBC, and SQL.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.