I have a proyect that use to load queries this:
@Query(value = SELECT_BY_USER_ID, nativeQuery = true)
Employee findByUserId(@Param(\"userId\") String userId);
If you need to load SQL from resources folder, you can try spring-data-sqlfile library. It supports loading SQL queries from resources. So you just need to put your SQL queries to the resources folder and than you can reference them in SqlFromResource annotation:
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
@SqlFromResource(path = "select_user_by_id.sql")
User findById(int userId);
}
The output will be like:
@Repository
public interface UserRepositoryGenerated extends JpaRepository<User, Integer> {
@Query(
value = "SELECT * FROM users WHERE id = :userId",
nativeQuery = true
)
User findById(int userId);
}
Unfortunately, spring data doesn't seem to support direct properties reference withing @Query anno (like in @Value). Despite that and assuming you use spring-data-jpa and Hibernate it is possible to use an external .xml file to store your queries as named queries and refer to them by method name, or like
@Query(nativeQuery = true, name="Repository1.query1")
This is a nice article on this matter : JPA Queries in XML File and it describes how to place your .xml file elsewhere than the expected orm.xml
Configured queries cannot be loaded from YML, as far as I know. They can be loaded from another file. Create a file in your resource project folder named /META-INF/jpa-named-queries.properties
and then place your query:
Employee.findById=select * from Employee e where e.id=?1
and then call your query:
@Query(name = "Employee.findById")
Employee findByUserId(String id);