spring h2 database dependency

  1. Add H2 Database Dependency in Maven or Gradle:
<!-- Maven -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- Gradle -->
implementation 'com.h2database:h2'
  1. Configure H2 Database in Spring Application Properties:
# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
  1. (Optional) Enable H2 Console (for development use):
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ServletRegistrationBean h2servletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());
        registrationBean.addUrlMappings("/h2-console/*");
        return registrationBean;
    }
}
  1. Access H2 Console: Open a browser and navigate to http://localhost:8080/h2-console. Use the configured JDBC URL (jdbc:h2:mem:testdb), username (sa), and password (password) to connect.

  2. Create Entities and Repositories as needed in your Spring application.

  3. Run and Test your Spring application with H2 Database.