JPQL and Native Queries with @Query
Write explicit JPQL and native SQL queries, bind named and positional parameters, and map projections.
Why @Query Exists
Spring Data JPA can derive queries from method names like findByLastName, but derived queries break down for anything non-trivial: joins across entities, aggregations, custom projections, or fine-tuned SQL.
The @Query annotation lets you attach an explicit query to a repository method. You write the query once, declaratively, and Spring binds the method's parameters and maps the result.
- JPQL — object-oriented query language that works against entities and fields.
- Native SQL — raw database SQL when you need vendor features or hand-tuned queries.
A Basic JPQL @Query
JPQL looks like SQL but operates on entity names and Java field names, not table and column names. Here User is the entity class and email is a Java field.
Notice the placeholder ?1 — this is a positional parameter bound to the first method argument.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.email = ?1")
Optional<User> findByEmailAddress(String email);
}All lessons in this course
- Derived Query Methods and Keyword Resolution
- JPQL and Native Queries with @Query
- Specifications and Criteria-Based Dynamic Filtering
- Pagination, Sorting, and Slice Streaming