Spring Boot With H2 Database

by Hayri Cicek


Posted on 25-Jul-2018

H2 is an open source relational database management system written in Java.
It can be embedded in Java applications or run in the client-server mode and it is easy to install and deploy.

Tools You Will Need
Maven 3.3+
Your favorite IDE. I'm using NetBeans
JDK 1.8+

Creating the Project With Spring Initializer
Go to start.spring.io and follow the steps below to generate a new project.



Enter the Details as Follows

Group: com.kodnito
Artifact: spring-boot-with-h2 
Dependencies: Web, H2, JDBC
Click Generate Project to generate and download your project.
Next, Unzip the downloaded zip file and import it into your favorite IDE.

H2 provides a web interface called H2 Console to see the data.
We can enable the console in /src/main/resources/application.properties


spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driver-class-name=org.h2.Driver

Create Schema and Data
In /src/main/resources/ create a file called schema.sql and type


create table todo (
    id integer not null,
    title varchar(255) not null,
    primary key(id)
);

Let's populate some data, create /src/main/resources/data.sql


insert into todo
values(1, 'Learn more Spring Boot');

insert into todo
values(2, 'Go buy milk');

Now when you open H2 Console http://localhost:8080/h2-console, you will now see that the todo table is created and the data is populated.


Share this: