【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;

    //构造方法
    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    //获取全部数据
    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    //通过ID查找
    @Override
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    //保存数据
    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    //删除数据
    @Override
    public 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;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 获取全部数据
    @GetMapping
    public 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";
    }

    //更改之后保存数据
    @PostMapping
    public 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

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

上一篇:迁移学习案例-python代码


下一篇:Pr 视频效果:时间