sprintboot实现增删改查的小demo

一、引入maven的依赖和starter

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
            <scope>runtime</scope>
        </dependency>
        <!--druid的依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

二、配置文件

application.yaml

spring:
  datasource:
    username: root
    password: 2020
    url: jdbc:mysql://localhost:3306/springboot01
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource #数据库连接池的类型


mybatis:
  mapper-locations: classpath:mapper/*.xml #对应mapper映射xml文件所在路径
  type-aliases-package: com.qcby.springbootinformation.entity #对应实体类路径

三、创建druid数据源注册类

DruidConfig类

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new DruidDataSource();
    }
}

四、开启下划线到驼峰命名的自动映射

MyBatisConfig

import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.qcby.springbootinformation.mapper")
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer getCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                // 开启下划线到驼峰命名的自动映射
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

五、数据库建表

/*
 Navicat Premium Data Transfer

 Source Server         : 本地数据库
 Source Server Type    : MySQL
 Source Server Version : 50649
 Source Host           : localhost:3306
 Source Schema         : springboot01

 Target Server Type    : MySQL
 Target Server Version : 50649
 File Encoding         : 65001

 Date: 07/01/2025 18:20:20
*/

    SET NAMES utf8mb4;
        SET FOREIGN_KEY_CHECKS = 0;

        -- ----------------------------
        -- Table structure for login
        -- ----------------------------
        DROP TABLE IF EXISTS `login`;
        CREATE TABLE `login`  (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
        `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
        PRIMARY KEY (`id`) USING BTREE
        ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact;

        -- ----------------------------
        -- Records of login
        -- ----------------------------
        INSERT INTO `login` VALUES (1, 'admin', '123');


        -- ----------------------------
        -- Table structure for user
        -- ----------------------------
        DROP TABLE IF EXISTS `user`;
        CREATE TABLE `user`  (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
        `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
        `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
        `gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
        `birth` date DEFAULT NULL,
        PRIMARY KEY (`id`) USING BTREE
        ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

        -- ----------------------------
        -- Records of user
        -- ----------------------------
        INSERT INTO `user` VALUES (1, '张三', '123', '北京', '男', '2020-06-14');
        INSERT INTO `user` VALUES (2, '李四', '234', '上海', '男', '2021-02-18');
        INSERT INTO `user` VALUES (3, '王五', '345', '天津', '女', '2018-06-07');
        INSERT INTO `user` VALUES (4, '赵六', '456', '保定', '女', '2021-06-28');

        SET FOREIGN_KEY_CHECKS = 1;

六、User实体类

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String address;
    private String gender;
    @DateTimeFormat(pattern = "yyyy-MM-dd") // 指定日期格式
    private Date birth;

    public User() {
    }

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

    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 String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

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

七、UserMapper接口

import com.qcby.springbootinformation.entity.User;

import java.util.List;

public interface UserMapper {

    /*
    * 查询所有
    * */
    List<User> findAll();

    /*
     * 添加
     * */
    int insert(User user);

    /*
    * 根据id查询
    * */
    User findById(int id);

    /*
    * 修改
    * */
    int update(User user);

    /*
    * 删除
    * */
    int delete(int id);
}

八、UserMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.springbootinformation.mapper.UserMapper"> <!--对谁进行操作就写谁-->

    <!--查询所有:List<User> findAll();-->
    <select id="findAll" resultType="user">
        select * from user;
    </select>

    <!--添加:int insert(User user);-->
    <insert id="insert" parameterType="user">
        insert into user(username,password,address,gender,birth)
        values(#{username},#{password},#{address},#{gender},#{birth})
    </insert>

    <!--根据id查询:User findById(int id);-->
    <select id="findById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

    <!--修改:int update(User user);-->
    <update id="update" parameterType="user">
        update user set
        username = #{username},
        password = #{password},
        address = #{address},
        gender = #{gender},
        birth = #{birth}
        where id = #{id}
    </update>

    <!--删除:int delete(int id);-->
    <delete id="delete" parameterType="int">
        delete from user where id = #{id}
    </delete>
</mapper>

九、UserService接口

import com.qcby.springbootinformation.entity.User;

import java.util.List;

public interface UserService {

    /*
     * 查询所有
     * */
    List<User> findAll();

    /*
     * 添加
     * */
    int insert(User user);

    /*
     * 根据id查询
     * */
    User findById(int id);

    /*
     * 修改
     * */
    int update(User user);

    /*
     * 删除
     * */
    int delete(int id);
}

十、UserServiceImpl实现类

import com.qcby.springbootinformation.entity.User;
import com.qcby.springbootinformation.mapper.UserMapper;
import com.qcby.springbootinformation.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 UserMapper userMapper;//这里报红没事

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }
    @Override
    public int delete(int id) {
        return userMapper.delete(id);
    }
}

十一、登录

实体类

public class Login {
    private Integer id;
    private String name;
    private String password;

    public Login() {
    }

    public Login(Integer id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

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

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

1.mapper接口

public interface LoginMapper {

    /*
    * 根据名字查询密码
    * */
    String selectByName(String name);
}

2.mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.springbootinformation.mapper.LoginMapper"> <!--对谁进行操作就写谁-->

    <!--根据名字查询密码:String selectByName(String name);-->
    <select id="selectByName" parameterType="String" resultType="String">
        select password from login where name = #{name}
    </select>
</mapper>

3.service接口

public interface LoginService {

    /*
     * 根据名字查询密码
     * */
    String selectByName(String name);
}

4.service实现类

import com.qcby.springbootinformation.mapper.LoginMapper;
import com.qcby.springbootinformation.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    LoginMapper loginMapper;

    @Override
    public String selectByName(String name) {
        return loginMapper.selectByName(name);
    }
}

5.controller

import com.qcby.springbootinformation.entity.User;
import com.qcby.springbootinformation.service.LoginService;
import com.qcby.springbootinformation.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.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    private UserService userService;


    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }

    /*
    * 登录
    * */
    @RequestMapping("/log")
    public String login(String name,String password,Model model){
        String pwd=loginService.selectByName(name);
        System.out.println("查到的密码:"+pwd);
        //必须要先判断null,否则会报空指针异常
        if(pwd==null){
            //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }else if(pwd.equals(password)){
            //登陆成功跳转到user.html
            List<User> users=userService.findAll();
            model.addAttribute("users",users);
            return "user";
        }else {
            //密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
}

十二、页面

1.登录页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <style>
        body{
            text-align: center;
            background-color: #f0f0f0;
        }
        label {
            font-size: 30px;
        }
        input {
            font-size: 25px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<h1>登录</h1>
<form th:action="@{/login/log}" method="post">
    <label for="name">用户名:</label><input id="name" name="name" type="text"/><br/>
    <label for="password">&nbsp;&nbsp;&nbsp;码:</label><input id="password" name="password" type="text"/><br/>
    <input type="submit" value="登录"/>
</form>
<p th:text="${msg}"></p>
</body>
</html>

2.用户列表页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表页面</title>
</head>
<style>
    table {
        width: 100%;
        border-collapse: collapse; /* 关键是这一行,确保边框不会重叠 */
    }
    th, td {
        border: 1px solid black; /* 为表格添加边框 */
        padding: 8px; /* 添加一些内边距 */
        text-align: center; /* 文本对齐方式 */
    }
    thead {
        background-color: #f2f2f2; /* 头部背景颜色 */
    }
    a {
        padding: 5px 10px;
        margin: 2px 5px 2px 2px;
        /*background-color: #82ccdd;*/
        color: white;
        /*元素内文本的水平对齐方式:居中*/
        text-align: center;
        /*去除下划线*/
        text-decoration: none;
        /*border: none;*/
        /*圆角边框*/
        border-radius: 5px;
        /*变成小手*/
        cursor: pointer;
    }
    #add {
        background-color: #2980b9;
        margin-bottom: 12px;
        display: inline-block;
        padding: 8px 12px;
    }
    .update{
        background-color: #8c7ae6;
    }
    .delete{
        background-color: #e74c3c;
    }
</style>

<body>

<a th:href="@{/user/toAdd}" id="add">添加</a>
<table>
    <thead>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>密码</th>
            <th>地址</th>
            <th>性别</th>
            <th>生日</th>
            <th style="width: 220px">操作</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="user:${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.username}"></td>
            <td th:text="${user.password}"></td>
            <td th:text="${user.address}"></td>
            <td th:text="${user.gender}"></td>
            <!--<td th:text="${user.birth}"></td>-->
            <td th:text="${#dates.format(user.birth, 'yyyy-MM-dd')}"></td>
            <td>
                <a th:href="@{/user/toUpdate/{id}(id=${user.id})}" class="update">修改</a>
                <a th:href="@{/user/delete/{id}(id=${user.id})}" th:onclick="return confirm('确定删除吗?')" class="delete">删除</a>
            </td>
        </tr>
    </tbody>
</table>

<p th:text="${msg}"></p>

</body>
</html>

3.添加页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加页面</title>
  <style>
    body{
      text-align: center;
      background-color: #f0f0f0;
    }
    label {
      font-size: 30px;
    }
    input {
      font-size: 25px;
    }
    input[type="text"],
    input[type="date"] {
      width: 300px;
      margin-bottom: 10px;
    }
  </style>
  <script>
    function back() {
      window.location.href = '/user/toUser';
    }
  </script>
</head>
<body>
<div>
  <h1>添加页面</h1>
  <form th:action="@{/user/add}" method="post">
    <label for="username">用户名:</label><input id="username" name="username" type="text"/><br/>
    <label for="password">&nbsp;&nbsp;&nbsp;码:</label><input id="password" name="password" type="text"/><br/>
    <label for="address">&nbsp;&nbsp;&nbsp;址:</label><input id="address" name="address" type="text"/><br/>
    <label for="birth">&nbsp;&nbsp;&nbsp;日:</label><input id="birth" name="birth" type="date"/><br/>
    <label for="gender">&nbsp;&nbsp;&nbsp;别:</label><input id="gender" name="gender" type="text"/><br/>
    <input type="submit" value="添加"/>
    <input type="button" th:onclick="back()" value="取消"/>
  </form>
</div>

</body>
</html>

4.修改页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改页面</title>
</head>
<style>
    body{
        text-align: center;
        background-color: #f0f0f0;
    }
    label {
        font-size: 30px;
    }
    input {
        font-size: 25px;
    }
    input[type="text"],
    input[type="date"] {
        width: 300px;
        margin-bottom: 10px;
    }
</style>
<script>
    function back() {
        window.location.href = '/user/toUser';
    }
</script>
<body>
<div>
    <h1>修改页面</h1>
    <form th:action="@{/user/update}" method="post" th:object="${user}">
        <!--th:field用于绑定表单字段的值和表单字段的名称。它会自动根据表单字段的名称和绑定的对象属性进行数据绑定-->
        <input type="hidden" th:field="*{id}" />

        <label for="username">用户名:</label>
        <input id="username" name="username" type="text" th:field="*{username}"/><br/>

        <label for="password">&nbsp;&nbsp;&nbsp;码:</label>
        <input id="password" name="password" type="text" th:field="*{password}"/><br/>

        <label for="address">&nbsp;&nbsp;&nbsp;址:</label>
        <input id="address" name="address" type="text" th:field="*{address}"/><br/>

        <label for="birth">&nbsp;&nbsp;&nbsp;日:</label>
        <input id="birth" name="birth" type="date" th:field="*{birth}"/><br/>

        <label for="gender">&nbsp;&nbsp;&nbsp;别:</label>
        <input id="gender" name="gender" type="text" th:field="*{gender}"/><br/>

        <input type="submit" value="修改"/>
        <input type="button" th:onclick="back()" value="取消"/>
    </form>

</div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值