When your SQL queries become huge, spring-data-sqlfile
helps you to load them from resources folder. It makes your code clean and you can work with well-formed SQL queries in your IDE.
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependency>
<groupId>com.github.VEINHORN.spring-data-sqlfile</groupId>
<artifactId>sqlfile-processor</artifactId>
<version>99228ac18b</version>
</dependency>
Just mark methods with SqlFromResource
annotation and provide valid path to the SQL query.
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
@SqlFromResource(path = "select_top_users.sql")
List<User> findAll();
@SqlFromResource(path = "select_user_by_id.sql")
User findById(int userId);
}
Recompile project and you'll give generated repository with SQL queries injected from resources folder. See example for more details.
@Repository
public interface UserRepositoryGenerated extends JpaRepository<User, Integer> {
@Query(
value = "SELECT * FROM users WHERE id = 2;",
nativeQuery = true
)
List<User> findAll();
@Query(
value = "SELECT * FROM users WHERE id = :userId",
nativeQuery = true
)
User findById();
}
spring-data-sqlfile
is an annotation processor which generates code during compile time.