3

Can we pass or input a .sql file to the Query annotation in Spring JPA?

Something like this @Query(file:/sql/employeeList.sql , nativeQuery=true)

/sql/employeeList.sql - i would like to put this file somewhere in the code, which will have the select sql in it.

I am not looking to have native sql string @Query("select abc....", nativeQuery=true) -- I dont want to use like this. because my sql is too huge.

3
  • 1
    Does this answer your question? Get query from file in SPRING BOOT using @Query Commented Jun 4, 2020 at 7:59
  • Seems like they are looking for the same in the above given link. but VEINHORN/spring-data-sqlfile is not spring provided libraries. I cannot use github libraries in office projects. Commented Jun 4, 2020 at 9:04
  • @jens-schauder normally you cannot use a resource file on @Query annotation but you can check this repo. You can just create your own JpaQueryMethodFactory that provides your own version of JpaQueryMethod. Commented Jan 30, 2023 at 13:00

3 Answers 3

1

@Jens Schauder is right you can't specify a sql file in Spring Data Jpa but as an alternative solution you could use this library https://github.com/VEINHORN/spring-data-sqlfile or you could simply load the file on your own.
Note: im using lombok on this example

@Component
@Slf4j
@AllArgsConstructor
public class ArticleBatchRepository {
  @PersistenceContext
  EntityManager em;

  public List<ArticleBatch> findAll(String articleId) {
  Query nativeQuery =  em.createNativeQuery(loadQuery("/db/queries/articles/BatchByWarehouse.sql"), ArticleBatch.class);
    nativeQuery.setParameter(1, articleId);
    return (List<ArticleBatch>) nativeQuery.getResultList();
  }

  private String loadQuery(String path) {
    try {
      InputStream is = this.getClass().getResourceAsStream(path);
      java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
      return s.hasNext() ? s.next() : "";
    } catch (Exception e) {
      log.error("Failed to load query {}: {}", path, e.getMessage(), e);
      return null;
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can't specify a sql file but Spring Data JPA will look in /META-INF/jpa-named-queries.properties to find named queries, which allows you to specify queries in a sql file.

This is described in this answer to a similar question.

Comments

0

You can check this repository.

You need to provide a JpaQueryMethodFactory bean to your configuration. You can extend the JpaQueryMethod class and override the getAnnotatedQuery and getRequiredAnnotatedQuery functions to read queries from the file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.