Connect to H2 Database
Overview
Almost every software system needs to store information. RDBMS is the de-facto standard for information storage. Several relational databases are available, and H2 has recently gained popularity.
What is H2 Database?
H2 is a relational database management system written in Java. It can be embedded in Java applications or run in client-server mode. It's an in-memory database, meaning information stored in DB is transient and cleared with the application.
H2 database is lightweight and excellent for POC and Test cases. The application can use any enterprise-grade database; however, a unit test for the data layer can use the H2 database.
Introduction to Spring Boot with H2 Database
Spring boot has strong integration with the H2 database, and most of the configurations are provided by default using auto-configurations. Spring boot uses the H2 database in embedded mode. As a result, database and application are part of the same process.
Dependencies
Only two dependencies are required for H2 DB configuration.
Maven dependency
Gradle Dependency
Configure H2 Database in Spring Boot Application
By default, Spring Boot configures the application to connect to an in-memory store with the username "sa" and an empty password.
However, we can change those parameters by adding the following properties to the application.properties file:
Initializing the DataSource
Database initialization is pre-step for any application. For example, if you have an employee management system, required tables should be pre-created so that the application can perform CRUD operations. Spring boot initializes the database automatically from the script in the `/resources folder.
- Create data.sql files in the resources folder.
data.sql
This arrangement should create an employee table in the H2 database as soon as the application starts.
Accessing the H2 Console with Spring Boot
H2 database has an embedded GUI 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
Then, after starting the application, we can navigate to http://localhost:8080/h2-console, which will present us with a login page.
Provide the same credential here that you kept in the property file.
Take your Java development to the next level with our Spring Boot FREE course. Enroll and bring your projects to life using the power of Spring Boot.
Conclusion
- H2 database is a lightweight in-memory database.
- H2 database is a good candidate for POC and test cases.
- Spring boot provides all the defaults to connect to the H2 database. Defaults can be overridden by providing required h2 specified properties in application.properties
- H2 has a web console that can be enabled using the spring boot property h2.console.enable to browse tables and run queries.