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 (87 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
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Spring boot h2 database dependency
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
Spring boot data jpa dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </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
3)Now please create repository for User class using @Repository annotation which is shown below
4)Now please add database connections in application.properties file which is shown below
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
6)Now please create a restcontroller for User entity which is shown below
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
9)if you want to see H2 console. Enter URL localhost:8080/h2-console/ which is shown below