Skip to content

H2 Database

José Miguel Rodríguez García edited this page Oct 26, 2021 · 2 revisions

Maven dependency

You must declare on pom.xml file the JAR dependency to use H2:

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

Configuration

Spring allows you to configure the parameters for any connection to a database through the application.properties file in resources folder. You can also declare the configuration in YAML format by creating an application.yaml file.

spring.datasource.url=jdbc:h2:mem:learning.spring.boot
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

With this configuration we are using a volatile memory database, in case the application is restarted all the information will be lost. In case you want to persist the database, you need to change the spring.datasource.url configuration and declare the path of the file where the changes will be persisted as soon as the JVM is stopped.

spring.datasource.url=jdbc:h2:file:./data/learning.spring.boot

Schema

H2 Console

H2 Console allows access to the database through the browser. By default its use is disabled.

spring.h2.console.enabled=true
spring.h2.console.path=/h2

The path is the relative path for the access to the console, in this case /h2.

Clone this wiki locally