H2 In-Memory Database Step by Step Tutorial

H2 In-Memory Database

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. h2.console.enabled=true
    2. datasource.platform=h2
    3. datasource.url=jdbc:h2:mem:<dbname>
    4. spring.jpa.hibernate.ddl-auto=update
  9. Run the application
  10. Visit http://localhost:8080/h2-console
  11. Change the jdbc url to what you already specified in the application.properties
  12. Click on Connect. Notice that the STUDENT table is created. This is made possible by springboot autoconfiguration
  13. Create a separate data.sql file in the resources folder. Write a query to insert a couple of records in the database
  14. Relaunch the application.
  15. Refresh the console and check that this initial data is inserted
  16. Autowire the StudentRepository into the StudentController
  17. Write a method getAllStudents in the Controller that uses the findAll() method of the repository to return all student records
  18. Add the @GetMapping of /students to the getAll Students method
  19. Write the getStudentByID method to return the student with a particular Id
  20. 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.

Leave a Reply

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