在 Spring Boot 应用程序中外部化查询 [英] Externalize query in spring boot application

查看:27
本文介绍了在 Spring Boot 应用程序中外部化查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 spring-boot 1.5.6 RELEASE.我想做一个基本的事情,将我的查询从存储库中的 @Query 注释移动到任何 xml 文件.

I am using spring-boot 1.5.6 RELEASE. I want to do a basic thing, move my queries from the @Query annotation in the repository to any xml file.

经过一些阅读,我发现我们可以使用 orm.xmljpa-named-queries.properties 来编写我的自定义查询.

After some reading, I figured out that we can use orm.xml or jpa-named-queries.properties to write my custom query.

我不明白这些 XML 文件必须存在于何处的文件结构.而且我的项目中没有 META-INF 文件夹.

I don't understand the file structure as to where these XML files have to be present. And I don't have a META-INF folder in my project.

示例:

POJO 类:

@Entity
public Class Customer {

private int id;
private String name;

// getters and setters
}

存储库:

public interface CustomerRepository extends PagingAndSortingRepository<Customer,Integer> {

// this query I need from an external xml file as it might be quite complex in terms of joins
@Query("Select cust from Customers cust")
public List<Customer> findAllCustomers();

}

参考 this堆栈溢出问题.我需要知道这些文件(orm.xmlpersistence.xml)需要存储在哪里,因为我没有 META-INF 文件夹.

Referred to this stackoverflow question. I need to know where these files (orm.xml and persistence.xml) need to be stored as I don't have a META-INF folder.

提前致谢!!

推荐答案

resources 文件夹内创建 META-INF .现在在 META-INF 文件夹中创建 jpa-named-queries.properties 文件.

Create META-INF inside resources folder . Now create jpa-named-queries.properties file inside that META-INF folder.

在这个属性文件中写你的查询,如下所示:

Write your query inside this properties file like this:

Customer.findAllCustomerByNamedQuery=从客户 c 中选择 c

其中Customer 表示实体类的名称,findAllCustomerByNamedQuery 是查询名称

Where Customer denote name of entity class and findAllCustomerByNamedQuery is the query name

在您的客户存储库中编写此代码以调用您在属性文件中编写的查询:

In your customer repository write this to call your query written in properties file:

列表<客户>findAllCustomerByNamedQuery();

这篇关于在 Spring Boot 应用程序中外部化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆