spring-data-sqlfile is a Java library that allows you to move large SQL queries from your Spring Data JPA @Query annotations into separate .sql files in your resources folder. This keeps your Java code clean and allows you to use SQL syntax highlighting and formatting in your IDE.
- Clean Code: No more multiline strings or messy SQL inside Java annotations.
- IDE Support: Full SQL syntax highlighting, auto-completion, and formatting for your queries.
- Maintainability: Manage complex queries as separate files.
- Automatic Generation: Uses annotation processing to generate the final repository at compile-time.
Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.veinhorn</groupId>
<artifactId>sqlfile-processor</artifactId>
<version>0.1.0</version>
</dependency>This library is also available via JitPack.
Add this to your pom.xml:
<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>v0.1.0</version>
</dependency>The library uses an Annotation Processor to scan your interfaces marked with @Repository. For every method annotated with @SqlFromResource, it reads the specified SQL file from your resources and generates a new interface (defaulting to the original name + Impl postfix) containing the @Query annotation with the injected SQL.
Create an interface and annotate its methods with @SqlFromResource. Provide the path to your SQL file relative to the resources folder.
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
@SqlFromResource(path = "sql/find_all_users.sql")
List<User> findAll();
@SqlFromResource(path = "sql/find_by_id.sql")
User findByUserId(Integer userId);
}Place your SQL files in src/main/resources/sql/.
src/main/resources/sql/find_all_users.sql:
SELECT * FROM users;src/main/resources/sql/find_by_id.sql:
SELECT * FROM users WHERE id = :userId;Run mvn clean compile. The annotation processor will generate UserRepositoryImpl in the target/generated-sources directory.
In your service, inject the generated UserRepositoryImpl interface:
@Service
public class UserService {
@Autowired
private UserRepositoryImpl repository; // Note the 'Impl' postfix
public List<User> getAllUsers() {
return repository.findAll();
}
}By default, the processor appends Impl to the generated interface name. You can customize this in your maven-compiler-plugin configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<compilerArgs>
<arg>-AclassPostfix=Generated</arg>
</compilerArgs>
</configuration>
</plugin>Now the generated interface will be named UserRepositoryGenerated.
For a complete working setup, check out the example module.
This project is licensed under the MIT License - see the LICENSE file for details.