Spring Boot application with H2 in-memory database and CRUD (Create, Read, Update, Delete) operations

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-08-07 13:17:56 Viewed : 435


Here is a complete example of a Spring Boot application with H2 in-memory database and CRUD (Create, Read, Update, Delete) operations for a Student entity.

  1. Create a Spring Boot Project: Start by creating a new Spring Boot project using Spring Initializr or your preferred IDE. Include the following dependencies: Spring Web, Spring Data JPA, H2 Database, and Thymeleaf (for simple UI).

  2. Configure Application Properties: Open the src/main/resources/application.properties file and add the following configuration:

properties
# H2 Configuration spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true # JPA Configuration spring.jpa.hibernate.ddl-auto=update
  1. Create the Entity Class: Create a Student entity class in the package com.example.demo.model:
java
package com.example.demo.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; // Constructors, getters, setters }
  1. Create the Repository Interface: Create a repository interface in the package com.example.demo.repository:
java
package com.example.demo.repository; import com.example.demo.model.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { }
  1. Create the Service Class: Create a service class in the package com.example.demo.service:
java
package com.example.demo.service; import com.example.demo.model.Student; import com.example.demo.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class StudentService { @Autowired private StudentRepository studentRepository; public List<Student> getAllStudents() { return studentRepository.findAll(); } public Optional<Student> getStudentById(Long id) { return studentRepository.findById(id); } public Student createStudent(Student student) { return studentRepository.save(student); } public Student updateStudent(Long id, Student updatedStudent) { if (studentRepository.existsById(id)) { updatedStudent.setId(id); return studentRepository.save(updatedStudent); } return null; } public void deleteStudent(Long id) { studentRepository.deleteById(id); } }
  1. Create the Controller: Create a controller class in the package com.example.demo.controller:
java
package com.example.demo.controller; import com.example.demo.model.Student; import com.example.demo.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping("/students") public class StudentController { @Autowired private StudentService studentService; @GetMapping public String getAllStudents(Model model) { List<Student> students = studentService.getAllStudents(); model.addAttribute("students", students); return "student-list"; } @GetMapping("/{id}") public String getStudentById(@PathVariable Long id, Model model) { studentService.getStudentById(id).ifPresent(student -> model.addAttribute("student", student)); return "student-details"; } @GetMapping("/add") public String showAddForm(Model model) { model.addAttribute("student", new Student()); return "student-form"; } @PostMapping("/add") public String addStudent(@ModelAttribute Student student) { studentService.createStudent(student); return "redirect:/students"; } @GetMapping("/edit/{id}") public String showEditForm(@PathVariable Long id, Model model) { studentService.getStudentById(id).ifPresent(student -> model.addAttribute("student", student)); return "student-form"; } @PostMapping("/edit/{id}") public String editStudent(@PathVariable Long id, @ModelAttribute Student updatedStudent) { studentService.updateStudent(id, updatedStudent); return "redirect:/students"; } @GetMapping("/delete/{id}") public String deleteStudent(@PathVariable Long id) { studentService.deleteStudent(id); return "redirect:/students"; } }
  1. Create HTML Templates (Thymeleaf): Create Thymeleaf HTML templates in the src/main/resources/templates directory:

    • student-list.html (List all students):
html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Student List</title> </head> <body> <h1>Student List</h1> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Actions</th> </tr> <tr th:each="student : ${students}"> <td th:text="${student.id}"></td> <td th:text="${student.name}"></td> <td th:text="${student.age}"></td> <td> <a th:href="@{/students/{id}(id=${student.id})}">View</a> <a th:href="@{/students/edit/{id}(id=${student.id})}">Edit</a> <a th:href="@{/students/delete/{id}(id=${student.id})}">Delete</a> </td> </tr> </table> <br> <a href="/students/add">Add Student</a> </body> </html>
  • student-details.html (View student details):
html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Student Details</title> </head> <body> <h1>Student Details</h1> <p>ID: <span th:text="${student.id}"></span></p> <p>Name: <span th:text="${student.name}"></span></p> <p>Age: <span th:text="${student.age}"></span></p> <a href="/students">Back to List</a> </body> </html>
  • student-form.html (Add/Edit student form):
html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title th:if="${student.id} ? `Edit Student` : `Add Student`"></title>
</head> <body> <h1 th:if="${student.id}">Edit Student</h1> <h1 th:unless="${student.id}">Add Student</h1> <form th:if="${student.id}" th:action="@{/students/edit/{id}(id=${student.id})}" th:object="${student}" method="post"> <input

Search
Sub-Categories
Related Articles

Leave a Comment: