Recipes
Recipe: Named Queries and Data Access
Named queries keep query text out of Java code. This recipe shows where the query lives, how parameters are bound and how the repository exposes the result.
A named query is a query with a stable name and a declared result type. The model stores the query text, its parameters and the type it returns. The data recipe then writes a repository method and the annotation or mapping that connects the method to the query.
Declaring a query
- Open the entity type that owns the data.
- Add a query element and give it a clear name, such as
findByEmail. - Write the query text and declare each parameter.
- Mark the query for generation and choose the return shape.
Parameter binding
Name parameters after the model attributes they compare against. The recipe maps a method argument to a named parameter, so a query that uses :email produces a method parameter called email. Keep the names identical across model, method and query. When names drift, the failure appears at startup rather than at build time.
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByEmail(String email);
long countByStatus(String status);
}
Return shapes
- Single entity. Use when the query returns at most one row.
- List of entities. Use for browse and search screens.
- Count. Use for dashboards and paging totals.
- Projection. Use when a screen needs only a few columns.
Queries that change often are better kept in a dedicated query type than in the entity. That keeps the entity stable and lets the repository grow without clutter.