Spring
Top 10 questions for @Query annotation in Spring Data
Questions and answers on custom JPQL and SQL queries, parameters, and pagination in Spring Data.
-
What is the
@Queryannotation used for in Spring?
Defines custom JPQL or native SQL queries in Spring Data JPA repositories for precise data retrieval or manipulation. -
How do you write a JPQL query using
@Query?
Use@Query("SELECT e FROM Entity e WHERE e.field = :param")in a repository method, binding parameters with@Param. -
Can
@Querybe used for native SQL queries?
Yes, setnativeQuery = truein@Queryto execute native SQL, e.g.,@Query(value = "SELECT * FROM table", nativeQuery = true). -
How do you pass parameters to
@Query?
Use:?or@Param("name"), e.g.,@Query("SELECT e FROM Entity e WHERE e.field = :name")with method parameter@Param("name") String value. -
What’s the difference between JPQL and native SQL in
@Query?
JPQL queries operate on entities and are database-agnostic; native SQL queries are database-specific and use raw SQL. -
How do you handle pagination with
@Query?
AddPageableas a method parameter, e.g.,@Query("SELECT e FROM Entity e") Page<Entity> findAll(Pageable pageable). -
Can
@Querybe used for update or delete operations?
Yes, with@Modifying, e.g.,@Modifying @Query("UPDATE Entity e SET e.field = :value")for updates. -
How do you use
@QuerywithLIKEin JPQL?
UseLIKEin the query, e.g.,@Query("SELECT e FROM Entity e WHERE e.field LIKE %:pattern%")for pattern matching. -
What happens if
@Querysyntax is incorrect?
Spring throws a runtime exception (e.g.,InvalidJpaQueryMethodException) during application startup or query execution. -
Can
@Queryreturn custom DTOs instead of entities?
Yes, use a constructor expression in JPQL, e.g.,@Query("SELECT new com.example.MyDto(e.field1, e.field2) FROM Entity e").