Spring Boot简易增删改查(CRUD)案例

项目架构

本项目为Spring Boot入门——增删改查案例。
前端采用html + thymeleaf模板代替jsp
项目架构如下:

.
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example
│   │   │       └── crud                          --业务功能模块 即 CRUD
│   │   │           ├── controller                --Controller层
│   │   │           │    └── UserControl           
│   │   │           ├── dao                       --Dao层
│   │   │           │    └── UserDao              --Dao层接口         
│   │   │           ├── pojo                      --数据模型
│   │   │           │    └── User                 --请求体
│   │   │           ├── service                   --Service层
│   │   │           │    ├── impl                 --Service层接口的实现
│   │   │           │    │    └── UserServiceImpl 
│   │   │           │    └── UserService          --Service层接口
│   │   │           └── Application.java          --启动类
│   │   └── resources
│   │       ├── static                            --静态资源
│   │       ├── template                          --模板
│   │              ├── add.html                   --增加用户页面
│   │              ├── index.html                 --主页面
│   │              └── modify.html                --修改用户页面
└── pom.xml                                       --项目依赖

数据库

MySQL:v8.0.29
Navicat Premium 15
新建连接:crud
新建数据库:springboot_crud
:user
包含三个字段:id,username,password

user表如下:

idusernamepassword
1Lebron1111
2Durant2222
3Curry3333
4Bryant4444
5Harden5555

建表SQL语句:

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

POJO

pojo下包含实体类User
实体类有三个私有成员变量:idusernamepassword
这三个属性分别与数据库springboot_crud中的表user相对应。
实体类User包含带参构造方法、无参构造方法、三个属性对应的getset方法,另外还包含一个重写的toString方法。

实体类User.java

package com.example.crud.pojo;

public class User {
    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User(Integer id,String username,String password) {
        this.id=id;
        this.username=username;
        this.password=password;
    }
    public User() {

    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
    
}

Dao

dao下包含接口UserDao
注解@Mapper用于修饰接口UserDao
注解@Insert、@Delete、@Update、@Select用于修饰接口内的方法(增删改查)。

UserDao.java

package com.example.crud.mapper;

import com.example.crud.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
	/**
     * 查询全部数据
     */
    @Select("select * from user")
    public List<User> findAll();
    
    **
     * 新增数据
     */
    @Insert("insert into user (username, password) values (#{username}, #{password})")
    public int save(User user);
    
	/**
     * 删除数据
     */
	@Delete("delete from user where id=#{id}")
	public int delete(int id);

	/**
     * 根据ID查找用户
     */
    @Select("select * from user where id=#{id}")
    public User get(int id);
    
    /**
     * 根据ID更新用户数据
     */
     @Update("update user set username=#{username},password=#{password} where id=#{id}")
     public int updateById(User user);
     
}

Service

service下包含包impl和Service层的接口UserService
其中,包impl包含Service层接口的实现类UserServiceImpl
Service层既需要调用Dao层接口,又需要提供接口给Controller层的类进行调用。

接口UserService.java

package com.example.crud.service;

import com.example.crud.pojo.User;

import java.util.List;

public interface UserService {
	/**
     * 查询全部数据
     */
     public List<User> findAll();

	/**
     * 新增数据
     */
	public int save(User user);
	
	/**
     * 删除数据
     */
    public int delete(int id);

    /**
     * 根据ID查找
     */
    public User get(int id);

    /**
     * 更新数据
     */
    public int updateById(User user);
    
}

接口实现类UserServiceImpl.java

package com.example.crud.service.impl;

import com.example.crud.mapper.UserMapper;
import com.example.crud.pojo.User;
import com.example.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}
	
	@Override
	public int save(User user) {
		return userDao.save(user);
	}

	@Override
	public int delete(int id) {
		return userDao.delete(id);
	}

	@Override
	public User get(int id) {
		return userDao.get(id);
	}

	@Override
	public int updateById(User user) {
		return userDao.updateById(user);
	}
	
}

Controller

controller包含类UserControl
注解@Controller用于修饰类UserControl
注解@Autowired表示自动注入Service层提供的接口,供Controller层使用。

UserControl.java

package com.example.crud.controller;

import com.example.crud.pojo.User;
import com.example.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
public class UserControl {
	
	@Autowired
	private UserService userservice;
	
	/**
	 * 查询所有用户数据
	 */
	@GetMapping("/index.html")
	public String userList(Map<String, List> result) {
		List<User> users = userService.findAll();
		result.put("users", users);
		return "index";
	}

	/**
     * 新增数据
     */
	@PostMapping("/add")
	public String save(User user) {
		userService.save(user);
		return "redirect:/index.html";
	}
	
	/**
     * 删除数据
     */
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable int id, HttpServletResponse servletResponse) throws IOExceptioon {
		userService.delete(id);
		System.out.println("----delete方法执行----");
		return "redirect:/index.html";
	}

	/**
	 * 根据id修改用户数据
	 */
	 @GetMapping("/updatePage/{id}")
	 public String updatePage(Model model, @PathVariable int id) {
	 	User users = userService.get(id);
	 	model.addAttribute("users", users);
	 	return "modify";
	 }
	
	@PutMapping("/update")
	public String updateUser(Model model, User user, HttpServletRequest request) {
		String id = request.getParameter("id");
		User userById = userService.get(Integer.parseInt(id));
		userService.updataById(user);
		System.out.println(user);
		return "redirect:/index.html";
	}
	
}

前端页面

resources下的包templates下有三个html文件。
⭐删除按钮添加了onclick="return confirm('确定删除?')"防止误操作。

主页面index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户信息主页面</title>
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<style>

    a{
        color: #ffffff;
    }
    h1{
        /*文字对齐*/
        text-align: center;
    }
    button{
        height: 50px;
        width: 50px;
        background-color: cornflowerblue;
    }
    .parent{
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .btn{
        width: auto;
    }

</style>

<body>
    <h1>Spring Boot增删改查</h1>
    <!--table-striped:斑马线格式,table-bordered:带边框,table-hover:鼠标悬停高亮-->
    <table class="table table-striped table-bordered table-hover text-center">
        <thead>
            <tr style="text-align:center">
                <!--th标签定义html表格中的表头单元格-->
                <th style="text-align:center">编号</th>
                <th style="text-align:center">用户名</th>
                <th style="text-align:center">密码</th>
                <th style="text-align:center">操作</th>
            </tr>
        </thead>
        <!--tr标签定义html表格中的所有行-->
        <!--遍历集合,如果被遍历的变量user为null或者不存在,则不会进行遍历,也不会报错-->
        <tr th:each="user:${users}">
            <!--td标签定义html表格中的标准单元格-->
            <td th:text="${user.id}"></td>
            <td th:text="${user.username}"></td>
            <td th:text="${user.password}"></td>
            <td>
                <!--a标签用来定义超链接 href表示超链接-->
                <a class="btn btn-primary" th:href="@{'/updatePage/'+${user.id}}">更改</a>
                <a class="btn btn-danger" th:href="@{'/delete/'+${user.id}}" onclick="return confirm('确定删除?')">删除</a>
            </td>
        </tr>
    </table>

    <div class="parent">
        <button type="button" class="btn btn-block"><a href="/add.html">添加用户</a></button>
    </div>

</body>

</html>

添加用户页面add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用户页面</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<sty>

<body>
	<div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
	    <form action="/add" method="post">
	        <!--form-control给input添加这个class后就会使用bootstrap自带的input框-->
	        用户名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
	        <!--注意参数的拼接-->
	        密 码:<input class="form-control" type="text" th:value="${password}" name="password"><br>
	        <button class="btn btn-primary btn-lg btn-block">保存</button>
	    </form>
	</div>
</body>
</html>

更改用户信息界面modify.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>更改用户信息界面</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
    <form action="/update" method="post">
        <!-- rest风格中的更新是put请求,所以这块先使用post请求,然后隐藏起来改为put请求-->
        <input name="_method" type="hidden" value="put">
        ID:<input class="form-control"  type="text" th:value="${user.id}" name="id"><br>
        用户名:<input class="form-control" type="text" th:value="${user.username}" name="username"><br>
        密 码:<input class="form-control" type="text" th:value="${user.password}" name="password"><br>
        <button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
    </form>
</div>

</body>
</html>

配置文件

application.yml

spring:
  web:
    resources:
      static-locations: classpath:/static/,classpath:/templates/
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/springboot_crud?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  mvc:
    hiddenmethod:
      filter:
        enabled: true
  devtools:
    restart:
      enabled: true # 设置开启热部署
  freemarker:
    cache: false # 页面不加载缓存,修改即使生效
mybatis:
  configuration:
    map-underscore-to-camel-case: true # 下划线驼峰设置
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   # 打印SQL语句

运行

在chrome浏览器中输入http://localhost:8080/index.html,即可进入用户信息主页面。

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值