Development Java springboot

How to configure the h2 database in Springboot?

H2 is an in-memory or file-based Java SQL database that is often used in Spring Boot applications for testing and development purposes. Configuring H2 database in a Spring Boot application involves the following steps:

  1. Add the H2 database dependency: To use H2 database in your Spring Boot application, you need to add the H2 database dependency to your project’s build file. You can add the following dependency to your pom.xml file:

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>

  1. Configure the H2 database properties: Once you have added the H2 database dependency to your project, you need to configure the H2 database properties in your Spring Boot application. You can add the following properties to your application.properties or application.yml file:

spring.datasource.driver-class-name=org.h2.Driver

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.username=sa

spring.datasource.password=

In the above configuration, we are specifying the driver class, database URL, username, and password for the H2 database.

  1. Enable the H2 console: To access the H2 database console, you need to enable it in your Spring Boot application. You can do this by adding the following configuration class to your project:

@Configuration

public class H2Configuration

{

@Bean

public ServletRegistrationBean h2servletRegistration()

{

ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());

registrationBean.addUrlMappings("/console/*");

return registrationBean;

}

}

  1. Run your application and test the H2 database: Finally, you can run your Spring Boot application and test the H2 database by accessing the H2 console at http://localhost:8080/console. In the console, you can create tables, insert data, and execute SQL queries to test the H2 database.

In summary, configuring the H2 database in a Spring Boot application involves adding the H2 database dependency, configuring the H2 database properties, enabling the H2 console, and testing the H2 database. With these configurations, you can use the H2 database in your Spring Boot application for testing and development purposes.

Author

Neil Kumar

Leave a comment

Your email address will not be published. Required fields are marked *