AvaTaylor
AvaTaylor

Reputation: 737

Spring Boot with H2 is running data.sql every time the web app starts, is this normal?

I have a Spring Boot application with embedded H2 database (configured to save database to disk).

I have a SQL file data.sql that creates a users table if it doesn't exist, and inserts an admin account in the users table.

The data.sql automatically runs when the app starts up, and everything works fine.

The problem is, it runs data.sql every time the application starts and it creates another admin record in the users table.

QUESTION: How do I configure it so it only runs data.sql when the database does not exist yet?

My settings in application.properties file look like this, so the data will get saved to disk, and run data.sql file to create the database ...

spring.datasource.url=jdbc:h2:file:./data/myapplication-1.0
spring.jpa.hibernate.ddl-auto=update

Upvotes: 0

Views: 1286

Answers (1)

MD Ruhul Amin
MD Ruhul Amin

Reputation: 4502

Spring Boot with H2 is running data.sql every time the web app starts, is this normal?

Yes! it is expected behavior. H2 is designed to load data each time if there exists any data.sql file. As because H2 is an inmemory database and expected that data will not persist after the program exit. Thats why data will be loaded each time. If you want some customization either you need to check it programatically or logic should exists(if value exists then update else insert) in data.sql file.

There are also easy way, after the data initialization, you set a new configuration value so that data will not loaded from data.sql file.

You can use the property spring.datasource.initialization-mode=never to stop loading database each time.

Reference: 79.3 Initialize a Database

Upvotes: 2

Related Questions