The @TemplateQuery annotation allows you to define dynamic native queries using external template files instead of writing JPQL/SQL in the repository interface. This enables MyBatis-like dynamic SQL capabilities.
1. Define the Repository
Extend GenericJpaRepository instead of the standard JpaRepository. Annotate your methods with @TemplateQuery.
public interface SampleRepository extends GenericJpaRepository<Sample, Long> {
@TemplateQuery
Page<Sample> findByContent(@Param("content") String content, Pageable pageable);
@TemplateQuery
CustomVO findCustomVO(@Param("id") Long id);
}
2. Create the Template File
Create a file in your classpath following the naming rule {EntityName}.sftl. By default, it looks in classpath:/sqls/. You can change this location using the property spring.jpa.template-location.
- Naming Rule:
{EntityName}.sftl. The EntityName is derived from the @Entity annotation or the class name. - Format:
.sftl files use Freemarker syntax mixed with SQL.
Example Sample.sftl:
--findByContent
SELECT * FROM t_sample WHERE 1=1
<#if content??>
AND content LIKE :content
</#if>
--findCustomVO
SELECT id,name as viewName FROM t_sample WHERE id=:id
3. IDE Support (IntelliJ IDEA)
To get syntax highlighting for .sftl files:
- Go to
Settings -> Editor -> File Types. - Find
Freemarker Template. - Register a new type named
*.sftl. - Choose a
Template Data Language (e.g., MYSQL).