This is Similar to the Spring with MVC Procedure
- Create a new Starter project. Add Web, jpa and H2 dependencies
- Examine the pom.xml
- Create a Student class in the models package
- Annotate the class with @Entity annotation, Annotate the the Id with @Id annotation and @GeneratedValue
- Create a StudentRepostory interface in the repositories package. Make it extend CrudRepository<T, Type>
- Create a StudentController in the controllers package. Annotate with @RestController
- Annotate the controller with @RequestMapping of /springh2
- Enable h2 console, datasource and url in the application.properties file
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:<dbname>
spring.jpa.hibernate.ddl-auto=update
- Run the application
- Visit http://localhost:8080/h2-console
- Change the jdbc url to what you already specified in the application.properties
- Click on Connect. Notice that the STUDENT table is created. This is made possible by springboot autoconfiguration
- Create a separate data.sql file in the resources folder. Write a query to insert a couple of records in the database
- Relaunch the application.
- Refresh the console and check that this initial data is inserted
- Autowire the StudentRepository into the StudentController
- Write a method getAllStudents in the Controller that uses the findAll() method of the repository to return all student records
- Add the @GetMapping of /students to the getAll Students method
- Write the getStudentByID method to return the student with a particular Id
- Test the application
Add Update and Delete Methods
- Write the Add Method
- Write the Update Method
- Write the Delete Method
- Test the application
- Use Advanced Rest Client to add some records
- Check Spring Console to see that the records are there
Implementing a Service Layer (You should be able to do this by now)
- To Implements a Service Layer, simply add a class called StudentService.
- Annotate this class with the @Service annotation
- Write the all the same methods you have in the controller file in in the service file. (without the @RequestMapping, @PathVariable or @RequestBody annotations
- Adjust the StudentController file so that it calls the functions in the StudentService file
- Modify the StudentService class to calls methods in the StudentRepository.
3 thoughts on “H2 In-Memory Database Step by Step Tutorial”