Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Query annotation - input a sql file

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.

like image 869
Charan Avatar asked Feb 15 '26 18:02

Charan


1 Answers

@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;
    }
  }
}
like image 53
Ivan Vilanculo Avatar answered Feb 19 '26 00:02

Ivan Vilanculo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!