To create a custom query using Spring Data JPA's @Query annotation, you can follow these steps:
-
Define your repository interface by extending one of the Spring Data JPA Repository interfaces, such as JpaRepository or CrudRepository.
-
Add the @Query annotation to a repository method. You can use JPQL (Java Persistence Query Language) or native SQL for the query.
Example using JPQL:
@Query("SELECT u FROM User u WHERE u.email = ?1")
List<User> findByEmail(String email);
Example using native SQL (with nativeQuery = true):
@Query(value = "SELECT * FROM users u WHERE u.email = ?1", nativeQuery = true)
List<User> findByEmailNative(String email);
- If you need to pass parameters to the query, you can use the
@Param annotation inside the repository method declaration. For example:
@Query("SELECT u FROM User u WHERE u.email = :email")
List<User> findByEmailWithParam(@Param("email") String email);
Remember that if you use native SQL queries, you should ensure that the provided statement is supported by your RDBMS, as Spring Data JPA doesn't adjust the query to the database's specific SQL dialect.