How can I configure spring-boot with h2database so as it reuses database each time I restart.
This is the only line I have in my application.properties file
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Persist the data in H2 Database If we want to persist the data in the H2 database, we should store data in a file. To achieve the same, we need to change the datasource URL property. In the above property, the sampledata is a file name.
Mainly, H2 database can be configured to run as inmemory database, which means that data will not persist on the disk. Because of embedded database it is not used for production development, but mostly used for development and testing.
H2 can be configured to run as an in-memory database, but it can also be persistent, e.g., its data will be stored on disk.
H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk.
You have to specify for spring.datasource.url
a value that specifies a filesystem DB. You can do it by using the jdbc:h2:file:
prefix.
For example, you could use this configuration to store the DB in a mydb.mv.db
file in the db
folder of your home
directory:
spring.datasource.url = jdbc:h2:file:~/db/mydb
Note that spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
is not required. The url and the H2 JDBC driver located in the classpath at runtime are enough.
Note also that by default, the database will be automatically created at startup if you use an embedded database (H2, HSQL or Derby).
It is the case even if you specify a file as database in the JDBC URL.
So to avoid recreating the db at each Spring Boot startup, you should also add :
spring.jpa.hibernate.ddl-auto = update
or
spring.jpa.hibernate.ddl-auto = validate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With