0

I am running a spring boot application where I have to run SQL statements that I have written .sql file is saved in the resource directory.

I don't want to run the script on the application startup. I have scheduler which run every 5 hour which does this job

Here is how my folder structure looks like

enter image description here

How can I pick those SQL files in my service class and execute those statements written in the file?

I am very new in spring boot I have used spring data JPA but never have executed SQL statements from the file. How to use Spring JDBC to do that?

How can I load these files in-service classes and execute them?

Learners
  • 121
  • 11
  • Check this link [How to run SQL scripts and get data on application startup?](https://stackoverflow.com/questions/39280340/how-to-run-sql-scripts-and-get-data-on-application-startup) for more detail. – Harrison Phan Apr 02 '22 at 13:00
  • @HarrisonPhan I already have looked at all the example but I don't want to run on application startup – Learners Apr 02 '22 at 13:02
  • https://stackoverflow.com/questions/29935451/execute-an-sql-file-in-unix-using-org-springframework-jdbc-datasource-init-scri –  Apr 02 '22 at 13:15
  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/init/ScriptUtils.html –  Apr 02 '22 at 13:15
  • ScriptUtils.executeSqlScript –  Apr 02 '22 at 13:15
  • I thought there is a way to do using spring JDBC or JPA ? – Learners Apr 02 '22 at 13:16
  • Look at where you are importing it from. org.springframework.jdbc.datasource.init.ScriptUtils –  Apr 02 '22 at 13:29
  • It says it is imported from jdbc package, which is a subpackage of springframework package. –  Apr 02 '22 at 13:30

1 Answers1

0

Try this:

import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.core.io.ClassPathResource;

ScriptUtils.executeSqlScript(connection, new ClassPathResource("sql/info/newInfo.sql"));

Reference.

  • How can i use this entityManager.createNativeQuery("sql2").executeUpdate(); – Learners Apr 02 '22 at 13:44
  • @Learners Use it according to where you found it from, if it doesn't work, try to fix it, if it doesn't get fixed, try something else. As simple as that :D –  Apr 02 '22 at 13:50
  • I was more looking to use Spring Data JPA to execute those queries present inside the SQL file. As there are multiple queries present inside that SQL file – Learners Apr 02 '22 at 14:01