The @Query annotation lets you write the query for a Spring Data repository method yourself, in JPQL or native SQL, instead of relying on the method name. Use it when a derived query like findByLastNameAndStatus becomes unreadable, needs joins, aggregates or database-specific features, or when you want an update or delete statement that runs in one round trip.
Spring Data JPA validates JPQL queries when the application context starts, so a typo in an entity or field name fails at startup instead of at the first request. That early feedback is one of the main reasons to prefer @Query over hand-built query strings.
@QuerynativeQuery = true@Modifying@Query or named queriesSpring Data JPA builds a query from the method name, for example findByEmailAndActiveTrue. This works well for two or three conditions. It stops working when you need any of the following:
JOIN FETCH to avoid N+1 selects.COUNT, SUM or GROUP BY with HAVING.UPDATE or DELETE statements.@Query solves these cases by attaching the query text directly to the repository method, so the intent stays next to the code that calls it.
@QueryJPQL works on entities and their fields, not on tables and columns. It is portable across databases supported by your JPA provider (Hibernate in most Spring Boot applications).
The text block (Java 15+) keeps long queries readable. join fetch loads the customer in the same SQL statement, which avoids one extra query per order. Named parameters (:country) bound with @Param are easier to maintain than positional ?1 placeholders, and both are sent to the database as bind parameters, so they are safe from SQL injection.
nativeQuery = trueSet nativeQuery = true when you need something JPQL cannot express, such as a PostgreSQL jsonb operator or a window function.
Native queries are tied to one database dialect and bypass JPQL validation at startup. Recent Spring Data JPA releases also provide a @NativeQuery shortcut annotation; check your version before relying on it. Prefer JPQL unless you have a concrete reason not to.
@ModifyingA @Query that changes data must also carry @Modifying, and it needs a transaction.
The method returns the number of affected rows. A bulk statement bypasses the persistence context, so entities already loaded in the current session can become stale. clearAutomatically = true clears the context after the update, and flushAutomatically = true flushes pending changes first.
@Query works with Pageable and Sort parameters. For queries with joins or grouping, supply a countQuery so Spring Data does not derive a wrong count.
You can also return a projection to select only the columns you need:
The constructor expression uses the fully qualified class name and builds the record directly, so no entities are loaded.
@Query or named queries| Approach | Best for | Checked at startup |
|---|---|---|
| Derived query (method name) | Simple lookups with up to about three conditions | Yes |
@Query with JPQL | Joins, aggregates, bulk updates, readable custom logic | Yes |
@Query with nativeQuery = true | Database-specific SQL | No |
@NamedQuery on the entity | Sharing one query across several places | Yes |
| Specifications or Querydsl | Dynamic filters assembled at runtime | Partly |
If the set of filters changes with user input, a fixed @Query is the wrong tool; use JpaSpecificationExecutor or Querydsl instead.
@Query protect against SQL injection?Yes, when you use parameters (:name or ?1). Values are bound as parameters. Concatenating strings into the query text, or using SpEL to splice raw input into it, removes that protection.
@Query without @Param?Yes, with positional parameters (?1, ?2). For named parameters, @Param is required unless you compile with the -parameters flag, which Spring Boot's Maven and Gradle plugins enable by default.
TransactionRequiredException?Modifying queries need an active transaction. Add @Transactional to the repository method or to the calling service method.
@Query for every custom query?No. Keep derived queries for simple cases and add @Query only where the method name would be long or the logic cannot be expressed by naming.
@Query attaches an explicit JPQL or native SQL statement to a Spring Data JPA repository method. Use JPQL for portable, startup-validated queries, native SQL only for database-specific features, @Modifying with a transaction for bulk changes, and countQuery for paged queries with joins. Keep derived queries for simple lookups.