Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer long query, written in external file, in Spring data jpa @Query

  • I want to write query (properties or yaml) in external file to load database. -
  • This is long query and does not look good to eye when placed inside @Query("long query") in XXXRepository class.
  • Is there way to write this query in an external file (properties, yaml, xml or json) and call that file in @Query() in spring data jpa?
like image 254
Ishtiaq Maqsood Avatar asked Jul 05 '17 23:07

Ishtiaq Maqsood


People also ask

What type of queries can be executed with the help of @query annotation?

The @Query annotation supports both JPQL and SQL queries.

Which language can be used to define queries when using the @query annotation in Spring Data?

The @Query annotation can be used to create queries by using the JPA query language and to bind these queries directly to the methods of your repository interface.

What are three methods to execute queries in JPA?

There are three basic types of JPA Queries: Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL syntax. Criteria API Query, constructed programmatically via different methods.


1 Answers

You can use named queries, where the queries have to be defined in a file called META-INF/jpa-named-queries.properties. See the spring example:

User.findBySpringDataNamedQuery=select u from User u where u.lastname=?1

Reference the query by name in the annotation in your repository, here the corresponding repository example from spring:

@Query(name = "User.findBySpringDataNamedQuery", countProjection = "u.firstname")
Page<User> findByNamedQueryAndCountProjection(String firstname, Pageable page);
like image 89
Ralf Stuckert Avatar answered Sep 24 '22 20:09

Ralf Stuckert