1

I have set up my Spring Boot application so that my H2 embedded database is populated at startup. I've done this by creating a data.sql file in the src/main/resources folder.

What I don't understand is what causes this to run at startup.

Also, I'd like to make this conditional - e.g. prevent it from executing when I'm running unit tests. Is this possible?

A similar question was asked here, but it is unresolved.

ksl
  • 4,519
  • 11
  • 65
  • 106
  • Do you want to load data based on spring profile? – Malakai Nov 19 '18 at 10:31
  • I don't know. I'm new to all this so still trying to figure it out. – ksl Nov 20 '18 at 11:29
  • quick and short explanation of how you can do it answered by me here: https://stackoverflow.com/questions/38040572/spring-boot-loading-initial-data/41644743#41644743 – Malakai Nov 20 '18 at 12:02
  • FUTURE READERS.. You can find a "spring profile" driven answer here : https://stackoverflow.com/questions/23790743/spring-boot-execute-data-sql-in-one-profile-only/67941530#67941530 – granadaCoder Jun 11 '21 at 18:50

1 Answers1

2

The mechanism that causes your data.sql file to be loaded is described in the Spring documentation in chapter 85.3 Database Initialization

The data.sql file name is the fallback filename when no scripts are set through the property spring.datasource.data (for a list of common spring properties go here and look for properties regarding datasource)

So for your usecase rename you dml scripts to something like data-default.sql and data-test.sql and set them profile specific in your application.yml or properties file.

C. Weber
  • 907
  • 5
  • 18
  • In addition I'd suggest to use high level DB migration utilities to set up your DB https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-use-a-higher-level-database-migration-tool – Sasha Shpota Nov 19 '18 at 11:00