Junior — Middle
How to formulate an SQL query for integration with Spring Data JPA repositories?
sobes.tech AI
Answer from AI
In Spring Data JPA, to integrate SQL queries with repositories, you can use the @Query annotation. It allows you to write native SQL or JPQL queries directly in the repository interface.
Example with a native SQL query:
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM users WHERE status = ?1", nativeQuery = true)
List<User> findByStatus(String status);
}
Example with a JPQL query:
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.status = ?1")
List<User> findByStatus(String status);
}
Thus, the SQL query is formed inside the @Query annotation, and Spring Data JPA automatically integrates it with the repository and executes it when the method is called.