In order to access a database from your Spring Boot application, you need a few things:

Certain Spring Data modules include the appropriate database drivers as a single selectable dependency from within the Spring Initializr. In other cases, such as when Spring uses the Java Persistence API (JPA) to access JPA-compliant datastores, it’s necessary to choose the Spring Data JPA dependency and a dependency for the target database’s specific driver, e.g., PostgreSQL.

To take the first step forward from memory constructs to persistent database, I’ll begin by adding dependencies, and thus capabilities, to our project’s build file.

H2 is a fast database written completely in Java that has some interesting and useful features. For one thing, it’s JPA-compliant, so we can connect our application to it in the same manner we would to any other JPA database like Microsoft SQL, MySQL, Oracle, or PostgreSQL. It also has in-memory and disk-based modes. This allows us some useful options after we convert from our in-memory ArrayList to an in-memory database: we can either change H2 to disk-based persistence or—since we’re now using a JPA database—change to a different JPA database. Either option becomes much simpler at that point.

To enable our application to interact with the H2 database, I’ll add the following two dependencies to the <dependencies> section of our project’s pom.xml:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

H2 Console

H2 database has an embedded GUI console for browsing the contents of a database and running SQL queries. By default, the H2 console is not enabled in Spring.

To enable it, we need to add the following property to application.properties:

spring.h2.console.enabled=true
spring.h2.console.settings.trace=false

The trace parameter value above hides all the H2 console trace in the application log. You can set it to true and look at how console actions are traced.

If you now run the application, you will see how the sampleDB is created and the console is enabled:

Untitled

As the log says, the database is available at the user's directory. You can open it and find the sampleDB.mv file there. It also says that now you can get to the h2 console at the localhost:8080/h2-console URL with your browser.

You can also change the /h2-console path in the application.properties file:

spring.h2.console.path=/h2

Untitled