liveBook · Manning

@Query

As explained in Spring Start Here, Second Edition

The @Query annotation declares the query expression that Spring Data uses to implement a repository method.

@Query declares the SQL that Spring Data runs for a repository method. It avoids relying on method-name rules to derive a query, so the method can be named for its purpose instead. section 14.3

Listing 14.6 Using the @Query annotation to specify the SQL query for an operation
public interface AccountRepository 
  extends CrudRepository<Account, Long> {
 
 
  @Query("SELECT * FROM account WHERE name = :name")    #A
  List<Account> findAccountsByName(String name);
 
}

This repository method selects accounts by name; the :name parameter must immediately follow the colon, with no intervening space. section 14.3

For queries that change data with UPDATE, INSERT, or DELETE, pair @Query with @Modifying. section 14.3

Updating an account

A repository method can use @Query("UPDATE account SET amount = :amount WHERE id = :id") to change an account’s amount; annotate that method with @Modifying. section 14.3

How Spring Start Here, Second Edition covers it

How deep it goes
Shows named SQL parameters and the @Modifying requirement, but does not detail query execution internals.
Examples
Demonstrates selecting accounts by name and updating an account amount.
What it assumes
Assumes familiarity with SQL and demonstrates the annotation through Spring Data repository methods.
What you can do after
Apply @Query in Spring Data repository methods to specify SQL, and pair data-changing queries with @Modifying.
How it connects
Connects Spring Data repositories with SQL queries, derived queries, and @Modifying.

Also explained in

Compare how 3 books explain @Query →

Related concepts

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