May 6, 2023
How to Configure the H2 Database in Spring Boot

H2 is an in-memory or file-based Java SQL database, and it's a popular choice for development and testing scenarios in Spring Boot projects since it needs no external database server to get running. Here's how to wire it up in four steps.
Step 1: Add the Dependency
Add the H2 database dependency to your pom.xml:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>Step 2: Configure the Datasource Properties
Add these settings to your application.properties (or the equivalent in application.yml):
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=Step 3: Enable the H2 Console
Register the H2 web console with a configuration class:
@Configuration
public class H2Configuration
{
@Bean
public ServletRegistrationBean h2servletRegistration()
{
ServletRegistrationBean registrationBean =
new ServletRegistrationBean(new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}Step 4: Test the Database
With the console mapping in place, open it in your browser at http://localhost:8080/console. From there you can create tables, insert data, and run SQL queries directly against the in-memory database — handy for quickly verifying your entity mappings and queries during development without standing up a separate database server.