Spring: H2 Database persistence

SteveOhio picture SteveOhio · Mar 17, 2017 · Viewed 20.7k times · Source

My application.properties:

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:./src/main/resources/asnDB;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.user=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create

I have a data.sql which is loaded when I start the spring-project.

How do I alter the application.properties to make the database persistent?

For now it always makes a new one. It doesn't work neither if I change the ddl.auto=create to ddl.auto=update. I know that ddl.auto=create overwrites my DB, but I have no idea how to make it persistent.

In the data.sql there are 3 Insert-Statements and when I run the project I already have 3 inserts in my DB. Then I insert a new one via my UI and quit the project. When i re-run the project there are just the initial 3 inserts. But there should be 4 inserts.

Answer

PowerFlower picture PowerFlower · Jun 19, 2017

You miss the auto-reconnect feature

spring.datasource.url=jdbc:h2:file:~/test2;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE

So that for example works:

spring.datasource.url=jdbc:h2:file:~/test2;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
spring.datasource.username=admin
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
#spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update