在 Springboot 中编写很长的@query 的干净方法

问题描述 投票:0回答:1

我在 JPA repo 函数的 @query 字段中有一个很长的 sql 本机查询。有没有一种干净的方法来编写查询,比如解析 SQL 文件并读取查询。

sql spring-boot jpa spring-annotations
1个回答
0
投票

是的,你可以做到。 首先使用您的查询创建一个 sql 文件并将该文件存储在资源文件夹中。

src/main/resources/your_sqlfile.sql

在 JpaRepository 函数中读取 sql 文件并使用类路径对象检索查询:

您可以关注以下代码:

import org.springframework.core.io.ClassPathResource;

public List<YourEntity> findByCustomQuery() {
    Resource resource = new ClassPathResource("mycustomquery.sql");
    String query = null;
    try {
        query = Files.readString(resource.getFile().toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.