0PricingLogin
Spring Boot 4 Complete Guide · Lesson

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

  1. Derived Query Methods and Keyword Resolution
  2. JPQL and Native Queries with @Query
  3. Specifications and Criteria-Based Dynamic Filtering
  4. Pagination, Sorting, and Slice Streaming
← Back to Spring Boot 4 Complete Guide