Spring MVC and Hibernate CRUD Example
In this article, we will be developing CRUD operations in Spring MVC and Hibernate. Hibernate is an object-relational mapping (ORM) framework. Developers use Hibernate to interact with databases using Java objects rather than SQL queries.
Spring MVC is a Model-View-Controller (MVC) framework used to build web applications in Java. The Spring MVC pattern has three parts:
- Model: The model contains the data that needs to be displayed on the view. A simple POJO class can be considered as a model.
- View: The view is used for rendering the UI Operations.
- Controller: The controller accepts user requests and passes them to the view for rendering.
Student Management System using Spring MVC and Hibernate CRUD
In this article, we will be creating a Student Management System using Spring MVC and Hibernate CRUD.
Prerequisites for the Topic:
- JDK 7
- MySQL Database
- IDE (Spring Tool Suite or Eclipse)
Steps to Setup a Project
Step 1: Create a Project
- Open Spring Initializr (https://start.spring.io/) to generate a simple project with the following dependencies:
- Spring Web
- Thymeleaf
- Spring Data JPA
- My SQL Database
XML
<? xml version = "1.0" encoding = "UTF-8" ?> < project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion >4.0.0</ modelVersion > < parent > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-parent</ artifactId > < version >3.2.0</ version > < relativePath /> <!-- lookup parent from repository --> </ parent > < groupId >com.spring</ groupId > < artifactId >Student_Management</ artifactId > < version >0.0.1-SNAPSHOT</ version > < name >Student_Management</ name > < description >Demo project for Student_Management</ description > < properties > < java.version >17</ java.version > </ properties > < dependencies > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa</ artifactId > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-webmvc</ artifactId > </ dependency > < dependency > < groupId >jakarta.servlet</ groupId > < artifactId >jakarta.servlet-api</ artifactId > < scope >provided</ scope > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-orm</ artifactId > </ dependency > < dependency > < groupId >jakarta.persistence</ groupId > < artifactId >jakarta.persistence-api</ artifactId > </ dependency > < dependency > < groupId >org.hibernate.orm</ groupId > < artifactId >hibernate-core</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-thymeleaf</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > < dependency > < groupId >com.mysql</ groupId > < artifactId >mysql-connector-j</ artifactId > < scope >runtime</ scope > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-test</ artifactId > < scope >test</ scope > </ dependency > </ dependencies > < build > < plugins > < plugin > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-maven-plugin</ artifactId > </ plugin > </ plugins > </ build > </ project > |
Project Structure:
Step 2: Database Configuration
- Add below code in “application.properties” file
# MySQL Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/student_management
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
# Hibernate Configuration
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
Note: Here we are Using MySQL database, but in Spring there are lots of Databases available so you can change configuration to database.
Step 3: Create a Model class – Student.java
Java
package com.demo.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Student { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; private String enrolledcourse; public Student() { super (); // TODO Auto-generated constructor stub } public Student(Long id,String name, int age,String enrolledcourse) { super (); this .id = id; this .name = name; this .age = age; this .enrolledcourse = enrolledcourse; } public Long getId() { return id; } public void setId(Long id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } public String getEnrolledcourse() { return enrolledcourse; } public void setEnrolledcourse(String enrolledcourse) { this .enrolledcourse = enrolledcourse; } } |
Step 4: Create a Repository Interface – StudentRepository.java
Java
package com.demo.repository; import com.demo.model.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { } |
Step 5: Create Service Interface – StudentService.java
Java
package com.demo.service; import com.demo.model.Student; import java.util.List; public interface StudentService { List<Student> getAllStudents(); Student getStudentById(Long id); void saveStudent(Student student); void deleteStudent(Long id); } |
Step 6: Create StudentService Implementation Class – StudentServiceImpl
Java
package com.demo.service; import com.demo.model.Student; import com.demo.repository.StudentRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Override public List<Student> getAllStudents() { return studentRepository.findAll(); } @Override public Student getStudentById(Long id) { return studentRepository.findById(id).orElse( null ); } @Override public void saveStudent(Student student) { studentRepository.save(student); } @Override public void deleteStudent(Long id) { studentRepository.deleteById(id); } } |
Step 7: Create StudentController Class – StudentController.java
Java
package com.demo.controller; import com.demo.model.Student; import com.demo.service.StudentService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping ( "/students" ) public class StudentController { @Autowired private StudentService studentService; @GetMapping public String listStudents(Model model) { List<Student> students = studentService.getAllStudents(); model.addAttribute( "students" , students); return "student/list" ; // This should match with the actual template path } @GetMapping ( "/add" ) public String showAddForm(Model model) { model.addAttribute( "student" , new Student()); return "student/add" ; } @PostMapping ( "/add" ) public String addStudent( @ModelAttribute ( "student" ) Student student) { studentService.saveStudent(student); return "redirect:/students" ; } @GetMapping ( "/edit/{id}" ) public String showEditForm( @PathVariable Long id, Model model) { Student student = studentService.getStudentById(id); model.addAttribute( "student" , student); return "student/edit" ; } @PostMapping ( "/edit/{id}" ) public String editStudent( @PathVariable Long id, @ModelAttribute ( "student" ) Student student) { studentService.saveStudent(student); return "redirect:/students" ; } @GetMapping ( "/delete/{id}" ) public String deleteStudent( @PathVariable Long id) { studentService.deleteStudent(id); return "redirect:/students" ; } } |
Step 8: Create a html files for UI interaction – add.html,edit.html,list.html
HTML
<!-- add.html --> <!DOCTYPE html> < html lang = "en" xmlns:th = "http://www.thymeleaf.org" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < link rel = "stylesheet" href = "/css/styles.css" > < title >Add Student</ title > </ head > < body > < div class = "container" > < center > < h1 >w3wiki</ h1 > </ center > < h2 >Add Student</ h2 > < form th:action = "@{/students/add}" th:object = "${student}" method = "post" > < label for = "name" >Name:</ label > < input type = "text" id = "name" name = "name" th:field = "*{name}" required> < label for = "age" >Age:</ label > < input type = "number" id = "age" name = "age" th:field = "*{age}" required> < label for = "age" >Enrolled Course:</ label > < input type = "text" id = "enrolledcourse" name = "enrolledcourse" th:field = "*{enrolledcourse}" required> < button type = "submit" >Save</ button > </ form > < br > < br > < a href = "/students" >Back to List</ a > </ div > </ body > </ html > |
HTML
<!-- list.html --> <!DOCTYPE html> < html lang = "en" xmlns:th = "http://www.thymeleaf.org" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < link rel = "stylesheet" href = "/css/styles.css" > < title >Student Management System</ title > </ head > < body > < div class = "container" > < center > < h1 >w3wiki</ h1 > </ center > < h2 >Student List</ h2 > < table > < thead > < tr > < th >ID</ th > < th >Name</ th > < th >Age</ th > < th >Enrolled Course</ th > < th >Edit</ th > < th >Delete</ th > </ tr > </ thead > < tbody > < tr th:each = "student : ${students}" > < td th:text = "${student.id}" ></ td > < td th:text = "${student.name}" ></ td > < td th:text = "${student.age}" ></ td > < td th:text = "${student.enrolledcourse}" ></ td > < td >< a th:href = "@{/students/edit/{id}(id=${student.id})}" >Edit</ a ></ td > < td >< a th:href = "@{/students/delete/{id}(id=${student.id})}" >Delete</ a ></ td > </ tr > </ tbody > </ table > < a href = "/students/add" >Add Student</ a > </ div > </ body > </ html > |
HTML
<!-- edit.html --> <!DOCTYPE html> < html lang = "en" xmlns:th = "http://www.thymeleaf.org" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < link rel = "stylesheet" href = "/css/styles.css" > < title >Edit Student</ title > </ head > < body > < div class = "container" > < center > < h1 >w3wiki</ h1 > </ center > < h2 >Edit Student</ h2 > < form th:action = "@{/students/edit/{id}(id=${student.id})}" th:object = "${student}" method = "post" > < input type = "hidden" th:field = "*{id}" > < label for = "name" >Name:</ label > < input type = "text" id = "name" name = "name" th:field = "*{name}" required> < label for = "age" >Age:</ label > < input type = "number" id = "age" name = "age" th:field = "*{age}" required> < label for = "age" >Enrolled Course:</ label > < input type = "text" id = "enrolledcourse" name = "enrolledcourse" th:field = "*{enrolledcourse}" required> < button type = "submit" >Save</ button > </ form > < a href = "/students" >Back to List</ a > </ div > </ body > </ html > |
Step 9: Create styles.css file for interactive UI Design -styles.css
CSS
/* styles.css */ body { font-family : 'Arial' , sans-serif ; background-color : #f5f5f5 ; margin : 20px ; } .container { max-width : 600px ; margin : 20px auto ; background-color : #fff ; padding : 20px ; border-radius: 8px ; } h 1 { color : #45a049 ; } h 2 { color : #333 ; } form { margin-top : 20px ; } label { display : block ; margin-bottom : 8px ; font-weight : bold ; } input { width : 100% ; padding : 8px ; margin-bottom : 12px ; border : 1px solid #ccc ; border-radius: 4px ; } button { background-color : #4caf50 ; color : #fff ; padding : 10px 15px ; border : none ; border-radius: 4px ; cursor : pointer ; } button:hover { background-color : #45a049 ; } table { width : 100% ; border-collapse : collapse ; margin-top : 20px ; } table, th, td { border : 1px solid #ddd ; } th, td { padding : 12px ; text-align : left ; } th { background-color : #4caf50 ; color : #fff ; } |
Steps to Run and Test Project
Now, you can run the Spring Boot application from IDE or by using the command-line tool provided by Spring Boot.
mvn spring-boot:run
Contact Us