在本文中,我们将在 Spring MVC 和 Hibernate 中开发CRUD 操作。 Hibernate 是一个对象关系映射(ORM)框架。开发人员使用 Hibernate 通过 Java 对象而不是 SQL 查询与数据库进行交互。
Spring MVC 是一个模型-视图-控制器 (MVC) 框架,用于用 Java 构建 Web 应用程序。 Spring MVC 模式分为三个部分:
- 模型: 模型包含需要在视图上显示的数据。一个简单的 POJO 类可以被视为一个模型。
- View:视图用于渲染 UI 操作。
- 控制器:控制器接受用户请求并将其传递给视图进行渲染。
使用 Spring MVC 和 Hibernate CRUD 的学生管理系统
在本文中,我们将使用 Spring MVC 和 Hibernate CRUD 创建一个学生管理系统。
该主题的先决条件:
- JDK 7
- MySQL数据库
- IDE(Spring 工具套件或 Eclipse)
依赖配置:
<?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>
|
- 在“application.properties”文件中添加以下代码
# MySQL 数据库配置 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 配置 spring.jpa.show-sql=true< i=8>spring.jpa.hibernate.ddl-auto=update
|
创建模型类——Student.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; } }
|
创建存储库接口 – StudentRepository.java
package com.demo.repository;
import com.demo.model.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { }
|
创建服务接口——StudentService.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); }
|
第6步:创建StudentService实现类——StudentServiceImpl
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); } }
|
第7步:创建StudentController类——StudentController.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"; } }
|
步骤 8:创建用于 UI 交互的 html 文件 – add.html、edit.html、list.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>jdon.com</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>
<!-- 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>jdon.com</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>
<!-- 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>jdon.com</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>
|
第9步:为交互式UI设计创建styles.css文件-styles.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; } h1{ color:#45a049 ; }
h2 { 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; }
|
运行和测试项目的步骤
现在,您可以从 IDE 或使用 Spring Boot 提供的命令行工具运行 Spring Boot 应用程序。
mvn spring-boot:run