How do you define a query in Spring Data JPA using @Query annotation?

How do you define a query in Spring Data JPA using @Query annotation?

A) By writing SQL queries directly in the @Query annotation
B) By using named queries defined in the entity class
C) By writing JPQL (Java Persistence Query Language) queries
D) Both A and C

Answer:

D) Both A and C

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.

Reference links:

Spring Data JPA Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top