Integrating Spring Boot with H2 In Memory Database

Hey Folks, I hope you are doing great. In this article, you will learn how to integrate H2 In-Memory database with your spring boot application. We will create rest service offering all CRUD operations in spring boot where some records will be initialized in H2 database table with the help of insert scripts.

What will you learn?

  • H2 In-Memory database – Few Words ?
  • Connecting H2 In-Memory database and Spring Boot
  • CRUD application in Spring Boot using H2 database

H2 In-Memory database – Few Words

H2 is a popular, open-source and relational database which is written in java. It is very convenient to use as it can be embedded in java application. It is widely used as In-Memory database but can be used as persistent data-store also.

In-Memory database is not persistent i.e. it is created when an application starts and destroyed when the application is stopped.

So, use H2 when you want to do a quick POC – Proof Of Concept as using persistent database like Oracle or SqlServer involves a lot of overheads.

Connecting H2 In-Memory database and Spring Boot

Spring Boot provides out-of-box support for H2. It requires very little configuration and is also easily maintainable. Just add H2 database jar as dependency in your pom.xml and you are ready to use it.

H2 Dependency
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

CRUD application in Spring Boot using H2 database

We will use SPRING INITIALIZR https://start.spring.io/ to bootstrap our Spring Boot application with H2 database. Provide “com.codeadda.h2.api” as Group, “spring-boot-h2-demo” as Artifact and “Web, JPA, DevTools, H2, Lombok” as Dependencies.

Once you are done with Group, Artifact and Dependencies, click on Generate Project button. Project will be downloaded as a zip file. Simply extract the project and import it into Eclipse.

Standard Maven Project

Full application will look like the following in the project explorer.

Project Dependencies

@Entity class Student

We create a simple Entity class Student with a primary key studId.  The @Id annotation indicates the member field below is the primary key of current entity. The @GeneratedValue annotation is to configure the way of increment of the specified column(field). Thanks to Lombok that generates all the boilerplate associated with your POJOs.  @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together.

Database script file with insert scripts

Create a database script file “data.sql” in “src/main/resources” folder with the following insert scripts that will be loaded in the In-Memory database table “Student” when the application is started.

Magic of Spring Boot with H2

H2 provides a convenient way of accessing the data through its web-based H2 console, then and there in your own browser. To access the H2 console, we have to enable the same  in the following way in /src/main/resources/application.properties file.

application.properties
# Enable web-based H2 Console
spring.h2.console.enabled=true

Now run the project as Java Application and you will be able to access the H2 console in your browser with the following url.

Remember to change the JDBC url to jdbc:h2:mem:testdb

H2 Console
http://localhost:8080/h2-console/

Just hit the “Connect” button and you will see the “Student” table already created. Run the select command to see the records for the insert scripts you kept in data.sql file.

JpaRepository

JpaRepository is the pre-defined core repository interface in Spring Data JPA enabling the basic CRUD functions on a repository. Important methods are shown below.

Lets use JpaRepository to manage the Student entity. Create IStudentRepository interface that will manage the Student entity with a primary key of type Integer. We have added findByStudGrade(String grade) method so that we will be able to get list all the students in the specified grade.

Create a controller class that exposes resources to the web.

Now create StudentController class annotated with @RestController that will expose web methods so that we can consume it. These web methods are capable of handling different HTTP-Methods.

In StudentController class we have used different annotations like @GetMapping, @PostMapping, @PutMapping and @DeleteMapping to be able to perform CRUD operations. Know about them briefly.

@GetMapping
  • Annotation used for mapping HTTP GET requests onto specific handler methods.
  • Acts as a shortcut for @RequestMapping(method = RequestMethod.GET)
@PostMapping
  • Annotation used for mapping HTTP POST requests onto specific handler methods that matches with the given URI expression..
  • Acts as a shortcut for @RequestMapping(method = RequestMethod.POST)
@PUTMapping
  • Annotation used for mapping HTTP PUTrequests onto specific handler methods.
  • Acts as a shortcut for @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping
  • Annotation used for mapping HTTP DELETE requests onto specific handler methods.
  • Acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE)

Bootstrap your application

SpringBootH2CrudApplication class will bootstrap the spring boot application and starts an instance of default Embedded tomcat server. spring-boot-h2-crud app will automatically get deployed in this embedded tomcat server and you will be able to access different handler methods and perform basic CRUD operations matching the URI expressions.

Now run the above SpringBootH2CrudApplication class as JavaApplication and start performing the basic CRUD operations. Let’s use the POSTMAN client to do this.

GEThttp://localhost:8080/getAllStudents

DELETEhttp://localhost:8080/removeStudent/101

POSThttp://localhost:8080/saveStudent

PUThttp://localhost:8080/updateStudent/102

GEThttp://localhost:8080/getStudent/Grade9

I hope you enjoyed this article. If you run into any problem, kindly let me know in the comment section below.

8 thoughts on “Integrating Spring Boot with H2 In Memory Database”

  1. Afroz says:

    Nicely explained with good example……

    1. Chandra Mani Gupta says:

      Thanks Afroz. Glad that you liked our article.

  2. Sanjay Kumar says:

    it saved me lot of time.Thanks for the post.

    1. Chandra Mani Gupta says:

      Thanks Sanjay. Kindly subscribe our blog for similar and other interesting articles.

  3. Amit Sharma says:

    very well elaborated,keep it up!

    1. Chandra Mani Gupta says:

      Glad that you find this useful.

  4. Saurav says:

    Excellent. Explained in depth with exact scenario.

    1. Chandra Mani Gupta says:

      Thanks that you liked my article.

Leave a Reply