How to use H2 database in spring boot

What you will learn here about Spring Boot

  • How to use H2 database in spring boot

Please click on below link to download sample project of H2 database with Spring boot.
download H2 database implementation with spring boot code (429 downloads)

How to use H2 database in spring boot

Please follow the following steps to know how to use h2 database in spring boot
1)Please create a simple maven project

2)Now please add following 3 maven dependencies in pom.xml which is shown below

Spring boot starter dependency


Spring boot h2 database dependency


Spring boot data jpa dependency


spring boot h2 database dependency

Note: Here You don’t have to create a table. Just define Entity, Spring boot will automatically create a table for you.

2)Now please create User class and use @Entity annotation on the top of User class which is shown below
Create Entity in spting boot

3)Now please create repository for User class using @Repository annotation which is shown below
create repository in spring boot

4)Now please add database connections in file which is shown below
h2 database connection spring boot

5)Now please create data.sql file in resources folder and add some insert SQL queries to add data into h2 database which is shown below
insert data into h2 database

6)Now please create a restcontroller for User entity which is shown below
create restcontroller in spring boot

7)Now please run your spring boot application

8)Now please go to browser and hit URL localhost:8080/users to get all users data which is shown below
get all users

9)if you want to see H2 console. Enter URL localhost:8080/h2-console/ which is shown below
h2 database console

You may also like...