Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring-boot Persistent h2database in filesystem

Tags:

spring-boot

h2

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

like image 723
Mcm Avatar asked Dec 20 '17 19:12

Mcm


People also ask

How do you persist H2 DB?

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.

Why H2 is not used in production?

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.

Where are H2 files stored?

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.

Is H2 in memory?

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.


1 Answers

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
like image 71
davidxxx Avatar answered Jan 04 '23 04:01

davidxxx