Learn

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.

Instructions

1.

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>
2.

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:

spring.datasource.url=jdbc:h2:~/plants.db spring.datasource.driverClassName=org.h2.Driver

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.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?