H2 database on Spring Boot: A beginner’s guide

Madhura Jayashanka
2 min readJul 5, 2023

--

H2 Database

The following topics will be covered in this article:

  • Introduction to the H2 database
  • Using the H2 database with Spring Boot
  • Conclusion
H2-Console view

Introduce the H2 database and its features

H2 is a relational database management system (RDBMS) with multiple benefits that operate in memory. Its lightweight design assures that it won’t add more complexity to your application, which is one of its biggest benefits. H2 is also quite effective, enabling your application to process data fast and efficiently.H2 allows you to concentrate on developing your application without being distracted by the administrative tasks of running a separate database server.

Using the H2 database with Spring Boot

You must include the H2 dependency to integrate the H2 database into your Spring Boot project. You can easily do this by including a new dependency to your pom.xml file in your SpringBoot project:

pom.xml file in Spring Boot Project
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

after you have added the dependency, you need to configure H2 in your Spring Boot application. You can do this by adding the following properties to your application.properties file located in src/main/resources/application.properties:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

These properties tell Spring Boot to use an in-memory H2 database named testdb. The username will be sa and no password is required. Now you are all set to use the H2 database!

Now you can access the database with:
http://localhost:8080/h2-console

Conclusion

In this article, we have shown you how to use the H2 database with Spring Boot. We have covered the following topics:

  • Introduction to the H2 database
  • Using the H2 database with Spring Boot

References

--

--