We are going to understand how to configure Spring Boot in order to connect with an H2 Database.
What is an H2 Database
H2 is a lightweight Java database.
It is tiny, simple, and can be embedded in our Spring Boot application easily.
The H2 DB does not need the installation of database servers or complex configurations.
H2 Database can be used in memory, without writing data on disk. This is useful for testing and temporary data storage during the development phases.
It is fast, open source pure writing in Java and supports standard SQL.
H2 is not recommended for data storage in production.
What dependencies do we need?
We are going to use these dependencies:
Spring Boot H2 Configuration
In order to configure Spring Boot, we need to add this property in our application.properties file.
spring.datasource.url=jdbc:h2:mem:testh2db spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.h2.console.enabled=true
Notice that we are configuring the DB in memory.
How to configure H2 to persist in a file?
We said that H2 is used in memory. However, we can also configure H2 to persist in a file.
# h2 file spring.datasource.url=jdbc:h2:file:test_h2_db # with path and file #spring.datasource.url=jdbc:h2:file:/home/dev/test_h2_db spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.h2.console.enabled=true
With this config, a file will be created and the data will be persisted in that file.
H2 URL Console
H2 provides a basic but convenient admin console with which we can visualize our database schema, tables, and data.
By default, the console is disabled, but with this property, you can enable it.
#enable console spring.h2.console.enabled=true
How to access to H2 GUI
When Spring Boot starts with this property evaluated in true, we will be able to see the H2 URL to access the admin console.
In this case, Spring Boot started in “localhost:8080” so the h2 URL is
If you want, you can change the default h2 URL /h2-console with this property.
In the init form, you have to change the JDBC URL, username, and password according to the information in the property file.
The H2 interface provides you access to the database in order to visualize and perform all the SQL queries you need.
H2 is an excellent solution to start developing an application faster, test it, and debug it.
We have seen how to configure and use an H2 database in Spring Boot both, in memory and in a file. Also how to open the H2 GUI in order to visualize and run SQL sentences.
Check the source code of this example here https://github.com/gustavopeiretti/spring-boot-examples
Thanks for your feedback :)