问题
- 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?
回答1:
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);
来源:https://stackoverflow.com/questions/44937306/how-to-refer-long-query-written-in-external-file-in-spring-data-jpa-query