Junior — Middle
What syntax can be used when applying the @Query annotation in Spring Data JPA?
sobes.tech AI
Answer from AI
The @Query annotation in Spring Data JPA allows writing custom JPQL or SQL queries directly in the repository.
- For JPQL queries (default):
@Query("SELECT u FROM User u WHERE u.email = ?1")
User findByEmail(String email);
- Using named parameters:
@Query("SELECT u FROM User u WHERE u.email = :email")
User findByEmail(@Param("email") String email);
- For native SQL queries (if needed):
@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)
User findByEmailNative(String email);
Thus, @Query provides flexible query definition using positional or named parameters, and allows choosing between JPQL and native SQL.