Skip to content
Model centric tools for Spring development Community portal
Skyway PerspectivesModel driven delivery

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.

Class diagram of the Skyway model repository with project, package, type and operation elements
Figure 2.20. Query definitions are model elements that the data recipe turns into repository methods.

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

  1. Open the entity type that owns the data.
  2. Add a query element and give it a clear name, such as findByEmail.
  3. Write the query text and declare each parameter.
  4. 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.
Performance. Add an index on every column used in a frequent filter. A named query is only as fast as the table behind it. Review the generated schema script and add indexes there so that regeneration keeps them.

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.