To connect to an embedded H2 database using Spring Data JPA, we’ll need to update your application’s properties. Spring uses a properties file to store information that your application depends on. The type of information that is typically stored inside properties files includes:
- the database URL
- the amount of logs your application should produce
- the “port” your application runs on
When our Spring Boot application starts, it will check the properties file, located at src/main/resources/application.properties, for any information that it might require to configure our application correctly.
To use the embedded H2 database, we’ll first need to add it as a dependency. In the same way that you added the
spring-boot-starter-data-jpa dependency, add another dependency:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
Now that we’ve added the correct dependency for using H2, we have to tell our application how to connect to it.
To connect to an embedded H2 database to run our application with, we will need to add the correct properties to the properties file.
Find the properties file for our application, and add the following lines:
This will tell Spring both where the database is stored, as well as what library it should use to “translate” our Java objects into SQL queries that H2 can understand.