Externalize query in spring boot application

ghz 1years ago ⋅ 225 views

Question

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.

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

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.

Example:

POJO Class:

@Entity
public Class Customer {

private int id;
private String name;

// getters and setters
}

Repository:

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();

}

EDIT: Referred to [this stackoverflow question](https://stackoverflow.com/questions/24931248/how-to-use-xml- configuration-for-named-queries-in-spring-data-jpa). 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.

Thanks in advance!!


Answer

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=Select c from Customer c

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:

List<Customer> findAllCustomerByNamedQuery();