Spring Boot provides easy integration with embedded databases like H2, HSQLDB, or Derby. This is particularly useful for development and testing purposes, where you might not want to set up and maintain a separate database instance.
To use an embedded database in a Spring Boot application, you need to include the appropriate database driver dependency in your project’s build configuration. For example, to use H2, you can include the following dependency in your pom.xml or build.gradle file:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
After including the dependency, you can configure the data source properties in your application properties file (application.yml or application.properties). For example, to configure an H2 in-memory database, you can use the following properties:
spring:
datasource:
url: jdbc:h2:mem:testdb
driverClassName: org.h2.Driver
username: sa
password: password
Once you have configured the data source, you can use it to create tables and perform CRUD operations like you would with a traditional database. For example, you can use Spring Data JPA with Hibernate to create entities and repositories, and Spring Boot will automatically configure the necessary components to use the embedded database.
In addition to providing a convenient way to set up and use an embedded database, Spring Boot also provides features like database initialization scripts and automatic schema generation based on entity classes. These can be useful for bootstrapping a new project or setting up a test environment.