Tuesday, August 20, 2024

When to use the @query annotation in Spring Boot?

 @Query Annotation

Purpose: The @Query annotation is used to define custom JPQL (Java Persistence Query Language) or SQL queries directly on repository methods in Spring Data JPA. This is particularly useful when you need more complex queries that cannot be easily expressed using Spring Data JPA’s method query derivation.

Usage: The @Query annotation is applied to repository methods in a Spring Data JPA repository interface. It allows you to specify the exact query to execute, which can be either JPQL or native SQL.

Syntax and Example

1.     JPQL Query:

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.username = :username")
    User findByUsername(@Param("username") String username);
}

2.     Native SQL Query:

public interface UserRepository extends JpaRepository<User, Long> {
    @Query(value = "SELECT * FROM users WHERE username = :username", nativeQuery = true)
    User findByUsernameNative(@Param("username") String username);
}

Parameters:

  • @Param("paramName"): Specifies the name of the parameter in the query. This is necessary for mapping method parameters to query parameters.
  • nativeQuery = true: Indicates that the query is a native SQL query rather than JPQL.

 

No comments:

Post a Comment