Spring Data JPA provides the option to execute native SQL queries as well. The following example demonstrates a simple native query in UserRepository:
@Query(value = "SELECT * FROM USERS WHERE u.name = ?1",
nativeQuery = true)
List<User> findUsersByNameNativeQuery(String name);
Important things to note are as follows:
- SELECT * FROM USERS WHERE u.name = ?1: This is the native SQL query to be executed. Note that we are not referring to the User entity but are using the table name users in the query.
- nativeQuery = true: This attribute ensures that the query is executed as a native query.