Junior — Middle
Kuidas koostada SQL-päring Spring Data JPA hoidlate integreerimiseks?
sobes.tech AI
Vastus AI-lt
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);
}
This way, the SQL query is formulated inside the @Query annotation, and Spring Data JPA automatically integrates it with the repository and executes it when the method is called.