2

I have a lengthy native query with several conditions and joins which runs into 25 lines.

Right now, I have it as an @Query annotation right near the method name in a Spring Data JPA repository interface.

What is the best way to externalize this in a Spring Boot project?

I had a look at entity named queries. However, it looks like the purpose there is different. Seems it is for attaching named queries with the Entity so that the query can be referred within JPA Queries in concise manner.

I have in the past used ClassPathResources to store static files like JSON responses for the purpose of testing. But, haven't come across a similar solution for Spring Data native queries.

Teddy
  • 4,009
  • 2
  • 33
  • 55
  • You mean to externalize it outside of the source code? e.g. to have it in a .properties file? – pleft Oct 18 '21 at 11:35
  • Yes, that's right @pleft – Teddy Oct 18 '21 at 11:36
  • 1
    Hmm and how are you going to treat the numerous arguments that your query method in your JPA repository expects? Externalizing the query will make it vulnerable to changes and those changes would affect the method's parameters. It won't be easy to distinguish if they are not close together. – pleft Oct 18 '21 at 11:39
  • That's true... it does make it easy to have them close. And with the IDE syntax highlighting, it doesn't look too bad either.. even 25 lines is not too big. But, wondering if there is a standard way to handle lengthier queries.. say saving them in .sql files – Teddy Oct 18 '21 at 11:48
  • 1
    This one is close: https://stackoverflow.com/questions/46060590/externalize-query-in-spring-boot-application/46060898 – Teddy Oct 18 '21 at 11:55

0 Answers0