Reputation: 31
I would like to create an app that fills a H2
database with some data on the first startup and persists it. Unless I remove the db file, the data is saved in the file and not overwritten. If I remove the db file, I would like the app to create it again with the basic set of data. I've made two files schema.sql
and data.sql
.
Schema.sql
CREATE TABLE IF NOT EXISTS ACCOUNT
(
id INT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(50) UNIQUE NOT NULL,
BALANCE INT NOT NULL
);
Data.sql
INSERT INTO ACCOUNT(NAME, BALANCE)
VALUES ('Wallet', 100);
INSERT INTO ACCOUNT(NAME, BALANCE)
VALUES ('Savings', 5000);
INSERT INTO ACCOUNT(NAME, BALANCE)
VALUES ('Budget3', 0);
INSERT INTO ACCOUNT(NAME, BALANCE)
VALUES ('Budget4', 0);
And my application.properties
spring.h2.console.path=/h2
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url = jdbc:h2:file:./data/sample;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
In the current setup, the data.sql does not populate the db on first start. If I add #spring.datasource.initialization-mode=always
- it populates the db on the first run, but causes issues afterwards.
Upvotes: 0
Views: 1655
Reputation: 1
i just tried with import.sql instead of data.sql and works for me
Upvotes: 0
Reputation: 151
If you are using schema.sql
and data.sql
you have to disable the spring.jpa.hibernate.ddl-auto
ie. spring.jpa.hibernate.ddl-auto=none
.
Take a look at the documentation on how to initialize the database.
Upvotes: 2