Java 使用@query从SPRING引导中的文件获取查询

Java 使用@query从SPRING引导中的文件获取查询,java,spring,oracle,yaml,Java,Spring,Oracle,Yaml,我有一个用于加载查询的项目: @Query(value = SELECT_BY_USER_ID, nativeQuery = true) Employee findByUserId(@Param("userId") String userId); “按用户ID选择”是一个普通的字符串查询 我在jar之外有一个YML配置,我用它来加载不同的配置,我想用这个YML来加载查询 示例YML: file: query1: SELECT * FROM DUAL; 但我不知道如何直接从@Query

我有一个用于加载查询的项目:

@Query(value = SELECT_BY_USER_ID, nativeQuery = true)
Employee findByUserId(@Param("userId") String userId);
“按用户ID选择”是一个普通的字符串查询

我在jar之外有一个YML配置,我用它来加载不同的配置,我想用这个YML来加载查询

示例YML:

file:
    query1: SELECT * FROM DUAL;
但我不知道如何直接从@Query value中的文件加载,我试着这样做:

@Query(value = ("${file.query1}"), nativeQuery = true)
List<Employee> findByCost();
@Query(value=(“${file.query1}”),nativeQuery=true)
列出findByCost();
我该怎么办?
谢谢。

据我所知,无法从YML加载配置的查询。它们可以从另一个文件加载。在资源项目文件夹中创建一个名为
/META-INF/jpa named queries.properties的文件,然后放置查询:

Employee.findById=select * from Employee e where e.id=?1
@Query(name = "Employee.findById")
Employee findByUserId(String id);
然后调用您的查询:

Employee.findById=select * from Employee e where e.id=?1
@Query(name = "Employee.findById")
Employee findByUserId(String id);

不幸的是,spring数据似乎不支持使用@Query anno(如@Value)直接引用属性。 尽管如此,假设您使用SpringDataJPA和Hibernate,也可以使用外部.xml文件将查询存储为命名查询,并通过方法名或类似方式引用它们

@Query(nativeQuery = true, name="Repository1.query1")

这是一篇关于这个问题的好文章:它描述了如何将.xml文件放置在预期orm.xml以外的其他位置。如果需要从resources文件夹加载SQL,可以尝试使用library。它支持从资源加载SQL查询。因此,您只需将SQL查询放入resources文件夹,然后就可以在SqlFromResource注释中引用它们:

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
    @SqlFromResource(path = "select_user_by_id.sql")
    User findById(int userId);
}
@存储库
公共接口用户存储库扩展了JpaRepository{
@SqlFromResource(path=“通过\u id.sql选择用户”)
用户findById(int userId);
}
输出如下所示:

@Repository
public interface UserRepositoryGenerated extends JpaRepository<User, Integer> {    
  @Query(
      value = "SELECT *     FROM users     WHERE id = :userId",
      nativeQuery = true
  )
  User findById(int userId);
}
@存储库
公共接口UserRepositoryGenerated扩展了JpaRepository{
@质疑(
value=“SELECT*FROM users,其中id=:userId”,
nativeQuery=true
)
用户findById(int userId);
}

如果我想调出ISDE资源文件夹?我的意思是,在jar之外。然后你应该在一个属性中设置你的查询,并使用一个带有JPA
EntityManager
的存储库。这是一个经过测试的库吗?它在社区中被广泛使用吗?@geneb。目前社区尚未积极使用它。