H2 In-Memory Database Step by Step Tutorial

This is Similar to the Spring with MVC Procedure

  1. Create a new Starter project. Add Web, jpa and H2 dependencies
  2. Examine the pom.xml
  3. Create a Student class in the models package
  4. Annotate the class with @Entity annotation, Annotate the the Id with @Id annotation and @GeneratedValue
  5. Create a StudentRepostory interface in the repositories package. Make it extend CrudRepository<T, Type>
  6. Create a StudentController in the controllers package. Annotate with @RestController
  7. Annotate the controller with @RequestMapping of /springh2
  8. Enable h2 console, datasource and url in the application.properties file




  1. Run the application
  2. Visit http://localhost:8080/h2-console
  3. Change the jdbc url to what you already specified in the application.properties
  4. Click on Connect. Notice that the STUDENT table is created. This is made possible by springboot autoconfiguration
  5. Create a separate data.sql file in the resources folder. Write a query to insert a couple of records in the database
  6. Relaunch the application.
  7. Refresh the console and check that this initial data is inserted
  8. Autowire the StudentRepository into the StudentController
  9. Write a method getAllStudents in the Controller that uses the findAll() method of the repository to return all student records
  10. Add the @GetMapping of /students to the getAll Students method
  11. Write the getStudentByID method to return the student with a particular Id
  12. Test the application

Add Update and Delete Methods

  1. Write the Add Method
  2. Write the Update Method
  3. Write the Delete Method
  4. Test the application
  5. Use Advanced Rest Client to add some records
  6. Check Spring Console to see that the records are there

Implementing a Service Layer (You should be able to do this by now)

  1. To Implements a Service Layer, simply add a class called StudentService.
  2. Annotate this class with the @Service annotation
  3. Write the all the same methods you have in the controller file in in the service file. (without the @RequestMapping, @PathVariable or @RequestBody annotations
  4. Adjust the StudentController file so that it calls the functions in the StudentService file
  5. Modify the StudentService class to calls methods in the StudentRepository.
User Avatar


Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

3 thoughts on “H2 In-Memory Database Step by Step Tutorial

  1. Pingback: HAL Browser and HATEOAS with Spring Boot Full Tutorial(Step by Step) – Trumpathon – News and information on latest top stories, weather, business, entertainment, politics,

Leave a Reply

Your email address will not be published. Required fields are marked *