Tutorial: Learn how to use the H2 Database with Spring Boot! 🤔
Tags: java, groovy, database, softwareengineering
Published: 2024-06-25 11:59:22

**In this [instructional](https://thospfuller.com/categories/tutorials/) we’ll review an example application which is written in the [Groovy Programming Language](https://www.groovy-lang.org/) and which demonstrates how to use the [H2 relational database](https://h2database.com/) ([H2 DB](https://h2database.com/) / [H2](https://h2database.com/)) with [Spring Boot](https://spring.io/projects/spring-boot).**

The benefit from using the [Groovy Programming Language](https://thospfuller.com/categories/software-engineering/groovy-programming-language/), in this case, is that it allows an [example](https://thospfuller.com/categories/examples/) to ship exactly one file which contains everything we need in order to run the application.

The [H2 Database Engine](https://h2database.com/) is a powerful [open-source](https://thospfuller.com/2023/12/28/database-change-notifications-in-the-h2-database/#what-is-the-h2-database-license-accordion-tab) [relational database](https://thospfuller.com/categories/software-engineering/relational-databases/) which is written in the [Java Programming Language](https://www.java.com/) and which is used with some frequency in [software development](https://thospfuller.com/categories/software-engineering/) projects — especially when it comes to testing applications.

Using [H2](https://h2database.com/) with the [Spring Framework](https://spring.io/projects/spring-framework) and with [Spring Boot](https://spring.io/projects/spring-boot), in particular, is a common use case, one which we’ll demonstrate here.

In the next section we’ll take a look at the [example](https://thospfuller.com/categories/examples/) and dissect, in detail, what happens in each step.

Note that in a few places I’ve added code which should not be required if we were to write this same solution using the [Java Programming Language](https://thospfuller.com/categories/software-engineering/java-programming-language/) and a properly structured [Maven](https://maven.apache.org/) project — I attempt to point this out, where appropriate.

## [H2 with Spring Boot Example on GitHub](https://gist.github.com/thospfuller/c0ac73cf450592ac262c2b098e65b4f6)

Included here is a link to the [GitHub gist](https://gist.github.com/thospfuller/c0ac73cf450592ac262c2b098e65b4f6) pertaining to the example used to demonstrate connecting the [H2 Relational Database](https://h2database.com/) with [Spring Boot](https://spring.io/projects/spring-boot) -- you should be able to paste this script into the [groovyConsole](https://groovy-lang.org/groovyconsole.html) and run as-is.

## Spring Boot With H2 DB Example Maven Dependencies

The following dependencies are used in this example:

1. [Spring Boot](https://mvnrepository.com/artifact/org.springframework.boot/spring-boot)
2. [Spring Boot AutoConfigure](https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure)
3. [Spring JDBC](https://mvnrepository.com/artifact/org.springframework/spring-jdbc)
4. [H2 Database Engine](https://mvnrepository.com/artifact/com.h2database/h2)
5. [Javax Annotation API](https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api)
6. [SLF4J Simple Provider](https://mvnrepository.com/artifact/org.slf4j/slf4j-simple)

The [Groovy Grape](https://docs.groovy-lang.org/latest/html/documentation/grape.html) dependency management system should find these dependencies automatically when the script is executed however for reference purposes I’ve included these here.

## An example pertaining to using the H2 Database Engine with Spring Boot

In this section we’ll take a look at the script in closer detail and go over what’s happening in each step.

Preconditions
In order to run this example, you will need the following:

- Java version 22.0.1 (required)
- Groovy 4.0.17 (required)
- groovyConsole (optional)

This script can be executed using Groovy alone hence the groovyConsole is optional.

The script uses the [Groovy Adaptable Packaging Engine](url) ([Groovy Grape](https://docs.groovy-lang.org/latest/html/documentation/grape.html)) to pull in dependencies from [Maven Central](https://central.sonatype.com/) hence a connection to the Internet is required as well.

I’ve included an example of what the output should look like when running this script from the command line here.

![H2 DB with Spring Boot Successful CRUD Example Output](https://thospfuller.com/wp-content/uploads/2024/06/h2-database-with-spring-boot-groovy-cli-example.png)

The **red arrow** points to the command used to run the script, and **orange arrow** points to the log statement that indicates the script is starting, and the **blue arrow** points to the log statement that indicates that the script has finished running.

In this example, the script runs a Spring Boot application that creates a table in the H2 DB, executes several CRUD (create, read, update, delete) operations on that table, and then drops the table.

The Groovy script runs to completion successfully and then exits.

### Step One: Declare a package.

When we define the Spring Boot Application, we’ll include the scanBasePackages setting, which requires a package name so we set that here.

![[Step One](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-one): Define a package for this script.](https://thospfuller.com/wp-content/uploads/2024/06/step-one-spring-boot-with-h2-db-package-declaration.png)

### Step Two: Add the Groovy Grape GrabConfig annotation.

In step two we need to add the Groovy Grape GrabConfig annotation and also set the systemClassLoader property to true — if we do not have this an exception will be thrown when the script is executed.

![[Step Two](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-two): Set the systemClassLoader to true for the GrabConfig for Groovy.](https://thospfuller.com/wp-content/uploads/2024/06/step-two-spring-boot-with-h2-database-systemclassloader-setting.png)

### Step Three: Grab dependencies and import required classes.

In step three we need to grab the dependencies necessary to run this example as well as import required classes — this includes the Spring Boot, H2 Database, and other supporting classes.

Note that we’re using the Hikari database driver in this example.

![[Step Three](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-three): Grab dependencies and import classes.](https://thospfuller.com/wp-content/uploads/2024/06/step-three-spring-boot-with-h2-example-imports.png)

See the [Maven Dependencies](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#maven-dependencies) section in this article for complete details.

### Step Four: Obtain a reference to an SLF4J logger.

We’re using the SLF4J log delegation framework in this example and we’ll send messages to console output so we can watch what’s happening as the script executes.

The HikariCP dependency is one other framework that we’re using that also uses SLF4J and we’ve included this high performance connection pooling implementation in this example.

![[Step Four](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-four): Get an instance of the SLF4J logger.](https://thospfuller.com/wp-content/uploads/2024/06/step-four-spring-boot-h2-db-get-slf4j-logger.png)

### Step Five: Configure H2 database datasource and JdbcTemplate beans.

In the fifth step we’ll configure the H2 Database datasource which utilizes the HikariCP high performance connection pool dependency as the datasource type.

Since this example demonstrates some simple CRUD operations executed against the H2 Database from a Spring Boot application, we’ll also configure an instance of JdbcTemplate here which uses this data source.

Note that we’re assigning the HikariDataSource class as the datasource type.

The H2 DB instance configured in this example will reside in-memory only — if we want to persist this information to disk then we need to change the URL.

![[Step Five](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-five): Review the configuration class for setting up the H2 in-memory database with HikariCP and JdbcTemplate in this example Spring Boot application.](https://thospfuller.com/wp-content/uploads/2024/06/step-five-declare-h2-db-datasource-and-jdbctemplate-bean-configurations.png)

### Step Six: Create a repository class.

In this step we implement a repository that contains the CRUD operations that we can execute on the H2 Database instance via the JdbcTemplate, which is autowired in this example by Spring Boot.

![[Step Six](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-six): The ExampleRepository class is a Spring Repository that manages a database table named "NAMES" and includes methods for creating and deleting the table, as well as adding, updating, deleting, and reading records.](https://thospfuller.com/wp-content/uploads/2024/06/step-six-h2-db-spring-boot-example-repository.png)

### Step Seven: Implement a service bean.

In this step we implement a transactional service bean which has stop and start lifecycle methods along with convenience methods that delegate to the repository bean.

The start method creates the example table in H2 when Spring Boot initializes the beans that the container is managing, and the stop method drops the example table before the container stops.

Other methods defined in the ExampleService deliver convenience and hide implementation details.

Using a service aids in reuse and is also helpful when testing our code.

![[Step Seven](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-seven): The ExampleService class handles database operations with transaction management using the ExampleRepository in this Example Spring Boot application.](https://thospfuller.com/wp-content/uploads/2024/06/step-seven-h2-db-spring-boot-example-service.png)

As the image has been truncated, refer to the [full example](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#complete-example) below or on the [GitHub Gist](https://gist.github.com/thospfuller/c0ac73cf450592ac262c2b098e65b4f6#file-h2-database-spring-boot-groovy-L137) for the complete implementation details.

### Step Eight: Implement the Spring Boot CommandLineRunner interface.

In this step we implement the Spring Boot CommandLineRunner specification.

Our implementation includes executing CRUD operations via the service created in [step seven](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-seven) against the H2 Database.

We log some information along the way so we can see what happens as each CRUD operation completes.

![[Step Eight](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-eight): Spring Boot CommandLineRunner implementation that demonstrates example H2 database operations.](https://thospfuller.com/wp-content/uploads/2024/06/step-eight-h2-db-spring-boot-example-commandlinerunner.png)

### Step Nine: Configure Spring Boot Application for Component Scanning

The code in the snippet defines a Spring Boot application and specifies the base package for component scanning.

![[Step Nine](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-nine): Spring Boot and H2 DB Example Application with Custom Component Scanning.](https://thospfuller.com/wp-content/uploads/2024/06/step-nine-h2-db-spring-boot-example-springbootapplication.png)

### Step Ten: Configure and then run the Spring Boot application.
The code in this snippet configures and then runs the Spring Boot application with the following configuration:

1. **Initialize SpringApplicationBuilder**: Creates a builder for the Spring Boot application using H2SpringBootExampleApplication.
2. **Set Profiles and Web Application Type**: Configures the application to use the default profile and disables the web environment (this is not a web application so we don’t need this).
3. **Set Parent Context**: Specifies the BeanConfiguration, ExampleRepository, ExampleService, and ExampleCommandLineRunner classes as components in the parent context.
4. **Run the Application**: Execute the application with the provided arguments.
5. **Close the Context**: Closes the application context — this step ensures that the stop lifecycle method in the service (see step six) is called before the Spring Boot example application has exited resulting in the names table in the H2 DB being dropped.

Finally, the script logs a completion message and then exits.

![[Step Ten](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#step-ten): Set up and run the Example Spring Boot application with specified components, profiles, and configurations, then close the application context and log completion.](https://thospfuller.com/wp-content/uploads/2024/06/step-ten-h2-db-spring-boot-example-run-application.png)

The next section includes the complete Spring Boot with H2 Database example script.

## Spring Boot With The H2 Database Engine Complete Example

Please refer to the [original article](https://thospfuller.com/2024/06/14/h2-database-with-spring-boot/#complete-example) or the [GitHub gist](https://gist.github.com/thospfuller/c0ac73cf450592ac262c2b098e65b4f6) for the complete example.

## Tutorial Conclusion

I hope that this instructional has provided adequate guidance as well as a useful [example](https://thospfuller.com/categories/examples/) regarding how to use the [H2 Database](https://h2database.com/) with [Spring Boot](https://spring.io/projects/spring-boot).

I have another guide that details [how to receive database event notifications from the H2 Database using triggers](https://thospfuller.com/2023/12/28/database-change-notifications-in-the-h2-database/) which may be of interest as well.