当前位置: 首页 > news >正文

【Java】SpringBoot实现MySQL数据库的增删查改

目录

1. 项目介绍

2. 相关代码

2.1 项目配置

2.2 SQL语句

2.3 数据访问层

2.4 业务逻辑层

2.5 Web表现层

3. 结果展示

4. 源码获取


1. 项目介绍

SpringBoot是一个轻量级框架,简化了Spring应用的开发和配置。相比较SSM框架,极大的简化了SSM中XML的配置。本项目基于SpringBoot框架,实现使用在HTML页面中对数据库中数据进行简单的操作。

2. 相关代码

2.1 项目配置

(1)Maven依赖配置

文件名:pom.xml

<!--Spring Data JPA-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--Thymeleaf-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--Spring Web-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--MySQL连接器-->
<dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope>
</dependency>
<!--lombok-->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
<!--Bootstrap-->
<dependency><groupId>org.webjars</groupId><artifactId>bootstrap</artifactId><version>5.3.3</version>
</dependency>
<!--SpringBoot 测试-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>

(2)SpringBoot配置

文件名:application.properties

spring.application.name=SpringBoot-CRUD
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.open-in-view=false

2.2 SQL语句

文件名:建表语句.sql

# 数据库
create database if not exists springboot;
use springboot;
# 数据表
create table user
(id   int auto_increment primary key,name varchar(255)     not null,age  tinyint unsigned not null
);
# 初始化数据
insert into user
values (null, '张三', 22),(null, '李四', 23),(null, '王五', 21)

2.3 数据访问层

(1)实体类

文件名:User.java

//实体类(Entity)
package pers.kenneth.springbootcrud.entity;import jakarta.persistence.*;
import lombok.Data;@Data
@Entity
@Table(name = "user")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(name = "name")private String name;@Column(name = "age")private Integer age;
}

(2)数据访问对象

文件名:UserRepository.java

//数据访问对象(Repository)
package pers.kenneth.springbootcrud.repository;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pers.kenneth.springbootcrud.entity.User;@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

2.4 业务逻辑层

(1)业务逻辑层接口

文件名:UserService.java

//业务逻辑层接口
package pers.kenneth.springbootcrud.service;import pers.kenneth.springbootcrud.entity.User;
import java.util.List;
import java.util.Optional;public interface UserService {//获取全部数据List<User> getAllUsers();//通过ID查找Optional<User> getUserById(Long id);//保存数据User saveUser(User user);//删除数据void deleteUser(Long id);
}

(2)服务类

文件名:UserServiceImpl.java

//服务类(Service)
package pers.kenneth.springbootcrud.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.kenneth.springbootcrud.entity.User;
import pers.kenneth.springbootcrud.repository.UserRepository;
import java.util.List;
import java.util.Optional;@Service
public class UserServiceImpl implements UserService {//业务逻辑层调用数据访问层private final UserRepository userRepository;//构造方法@Autowiredpublic UserServiceImpl(UserRepository userRepository) {this.userRepository = userRepository;}//获取全部数据@Overridepublic List<User> getAllUsers() {return userRepository.findAll();}//通过ID查找@Overridepublic Optional<User> getUserById(Long id) {return userRepository.findById(id);}//保存数据@Overridepublic User saveUser(User user) {return userRepository.save(user);}//删除数据@Overridepublic void deleteUser(Long id) {userRepository.deleteById(id);}
}

2.5 Web表现层

(1)控制器

文件名:UserController.java

//控制器(Controller)
package pers.kenneth.springbootcrud.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.kenneth.springbootcrud.entity.User;
import pers.kenneth.springbootcrud.service.UserService;@Controller
@RequestMapping("/users")  //访问:http://localhost:8080/users
public class UserController {//controller层调用业务逻辑层private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}// 获取全部数据@GetMappingpublic String listUsers(Model model) {model.addAttribute("users", userService.getAllUsers());System.out.println(model.getAttribute("users"));return "users";}//通过ID查找,点击进入更新数据界面@GetMapping("/{id}")public String getUser(@PathVariable Long id, Model model) {model.addAttribute("user", userService.getUserById(id).orElse(null));return "update-user";}//点击进入添加数据界面(并传递一个初始化的user对象)@GetMapping("/add")public String addUser(Model model) {model.addAttribute("user", new User());return "add-user";}//更改之后保存数据@PostMappingpublic String saveUser(User user) {userService.saveUser(user);return "redirect:/users";}//删除之后保存数据@GetMapping("/delete/{id}")public String deleteUser(@PathVariable Long id) {userService.deleteUser(id);return "redirect:/users";}
}

(2)用户数据页面

文件名:users.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head><meta charset="UTF-8"><!--bootstrap框架--><link rel="stylesheet" href="/webjars/bootstrap/5.3.3/css/bootstrap.min.css"><script src="/webjars/bootstrap/5.3.3/js/bootstrap.min.js"></script><title>用户</title>
</head>
<body>
<div class="container"><table class="table table-striped table-hover table-bordered"><thead><tr><th scope="col">ID</th><th scope="col">姓名</th><th scope="col">年龄</th><th scope="col">操作</th></tr></thead><tbody class="table-group-divider"><tr th:each="user : ${users}"><td th:text="${user.id}"></td><td th:text="${user.name}"></td><td th:text="${user.age}"></td><td><a th:href="@{/users/delete/{id}(id=${user.id})}">删除</a><a th:href="@{/users/{id}(id=${user.id})}">更改</a></td></tr></tbody></table><a href="/users/add">添加用户</a>
</div>
</body>
</html>

(3)添加数据页面

文件名:add-user.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head><meta charset="UTF-8"><title>添加用户</title>
</head>
<body>
<form action="/users" method="post"><input type="hidden" name="id" th:value="${user.id}">姓名:<input type="text" name="name" th:value="${user.name}"><br>年龄:<input type="text" name="age" th:value="${user.age}"><br><input type="submit" value="提交">
</form>
</body>
</html>

(4)更改数据页面

文件名:update-user.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head><meta charset="UTF-8"><title>更新用户</title>
</head>
<body>
<form action="/users" method="post"><input type="hidden" name="id" th:value="${user.id}">姓名:<input type="text" name="name" th:value="${user.name}"><br>年龄:<input type="text" name="age" th:value="${user.age}"><br><input type="submit" value="提交">
</form>
</body>
</html>

3. 结果展示

(1)用户数据页面

(2)添加数据页面

(3)更改数据页面

4. 源码获取

GitHub:https://github.com/KennethCreative/SpringBoot-CRUD.git

Gitee:https://gitee.com/KennethCreative/SpringBoot-CRUD.git

# GitHub
git clone https://github.com/KennethCreative/SpringBoot-CRUD.git
# Gitee
git clone https://gitee.com/KennethCreative/SpringBoot-CRUD.git

若有不妥之处,恳请读者批评指正


http://www.mrgr.cn/news/57792.html

相关文章:

  • RAG技术
  • 【STM32项目_1_基于 STM32 的智慧门禁系统】
  • webpack生成的SourceMap更改生成路径
  • DevEco Studio的使用 习题答案 HarmonyOS第一课
  • npm使用
  • PyTorch求导相关
  • 【ROS2】在启动文件launch中,配置节点崩溃后自动重启
  • 编程中的注意事项
  • 打印一张A4纸多少钱?
  • 精品推荐 | StarPure石蜡包埋样本DNA提取试剂盒
  • Linux:sh脚本
  • 【读书笔记·VLSI电路设计方法解密】问题21:为什么降低芯片的功耗如此重要
  • vuetify页面布局
  • Spring事务详解——面试必看!
  • 常见的磁盘挂载方式
  • 软考中级网络工程师,快背,都是精华知识点!
  • 基于vue框架的的高校设备信息管理系统的设计与实现tx6d7(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
  • k8s 部署步骤整理(containerd)
  • C# 创建型设计模式之----单例模式
  • 牛马阅读《SpFormer: Spatio-Temporal Modeling for Scanpaths with Transformer》
  • 记录如何在RK3588板子上跑通paddle的OCR模型
  • 美畅物联丨构建卓越智慧物联中台的三大核心要素
  • win10安装idk8点击下一步没反应点击下一步闪退,win10安装jdk8失败
  • 蚁剑连接本地木马文件报错
  • Elasticsearch如何搜索日志并存储
  • Spring Boot集成PageHelper分页插件详解---补充