How do you define a query in Spring Data JPA using @Query annotation?
Answer:
Explanation:
The @Query
annotation in Spring Data JPA is used to define custom queries directly within repository interfaces. You can write SQL or JPQL (Java Persistence Query Language) queries using this annotation. JPQL is similar to SQL but operates on entity objects and their fields rather than directly on database tables and columns.
For example:
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.email = ?1")
User findByEmail(String email);
}
In this example, the @Query
annotation is used to define a JPQL query that retrieves a User
entity based on the email address. The findByEmail()
method will execute this query when called, returning the matching User
object.
You can also write native SQL queries if needed by setting the nativeQuery
attribute to true
:
@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)
User findByEmailNative(String email);
The @Query
annotation provides flexibility in defining custom queries, allowing developers to optimize and tailor data retrieval as needed.