ToB企服应用市场:ToB评测及商务社交产业平台

标题: Spring boot + Mybatis 实现数据库的增删改查(CRUD)操纵 [打印本页]

作者: 张裕    时间: 2024-10-15 02:45
标题: Spring boot + Mybatis 实现数据库的增删改查(CRUD)操纵
Spring boot + Mybatis 实现数据库的增删改查(CRUD)操纵

利用 Spring boot,我们可以快速构建 Spring 框架应用。利用 Mybatis 为 Spring boot 提供的依赖,我们可以快捷地毗连到 MySQL,实现 web 项目对数据库的 CRUD 操纵。
一、创建项目

在 IDEA 中新建 maven 项目,并在 pom.xml 中导入 Spring boot,Mybatis 相关依赖:

  1. <!-- 导入Spring boot父包 -->
  2. <parent>
  3.   <groupId>org.springframework.boot</groupId>
  4.   <artifactId>spring-boot-starter-parent</artifactId>
  5.   <version>3.3.2</version>
  6. </parent>
  7. <dependencies>
  8.                   <!-- 导入Spring  -->
  9.       <dependency>
  10.           <groupId>org.springframework.boot</groupId>
  11.           <artifactId>spring-boot-starter-web</artifactId>
  12.       </dependency>
  13.                   <!-- 导入Mybatis -->
  14.       <dependency>
  15.           <groupId>org.mybatis.spring.boot</groupId>
  16.           <artifactId>mybatis-spring-boot-starter</artifactId>
  17.           <version>3.0.3</version>
  18.       </dependency>
  19.                   <!-- 导入MySQL -->
  20.       <dependency>
  21.           <groupId>mysql</groupId>
  22.           <artifactId>mysql-connector-java</artifactId>
  23.           <version>8.0.33</version>
  24.       </dependency>
  25.                   <!-- lombok可以自动生成getter和setter -->
  26.       <dependency>
  27.           <groupId>org.projectlombok</groupId>
  28.           <artifactId>lombok</artifactId>
  29.           <version>1.18.32</version>
  30.       </dependency>
  31.   </dependencies>
复制代码
在 MySQL 中新建一个示例数据库 studentsql,实验以下建表语句:
  1. create table student(
  2.         id int,
  3.   name varchar(10),
  4.         major        varchar(10) ,
  5.         primary key (id)
  6. )
  7. insert into student values(1,"张三","中文");
  8. insert into student values(2,"李四","新闻");
  9. insert into student values(3,"王五","计算机科学与技术");
复制代码
在项目目次 main/java 下新建包 com.busyforest.entity,用于存放实体类。
在 entity 包下新建实体类 Student:
  1. package com.busyforest.entity;
  2. import lombok.Data;
  3. @Data
  4. public class Student {
  5.     private int id;
  6.     private String name;
  7.     private String major;
  8. }
复制代码
在项目目次 main/java 下新建包 com.busyforest.inter,用于存放接口。
在 inter 包下新建接口 StudentInterface:
  1. package com.busyforest.inter;
  2. import com.busyforest.entity.Student;
  3. import java.util.List;
  4. public interface StudentInterface {
  5.     public List<Student> getAllStudents();
  6.     public Student findStudentById(int id);
  7.     public void addNewStudent(Student student);
  8.     public void updateStudent(Student student);
  9.     public void deleteStudentById(int id);
  10. }
复制代码
在项目目次 main/java 下新建包 com.busyforest.controller,用于存放控制类,处置惩罚 http 哀求。
在 controller 包下新建控制类 StudentHandler:
  1. package com.busyforest.controller;
  2. import com.busyforest.entity.Student;
  3. import com.busyforest.inter.StudentInterface;
  4. import org.springframework.web.bind.annotation.*;
  5. import java.util.List;
  6. @RestController
  7. @RequestMapping("/student")
  8. public class StudentHandler {
  9.           @Autowired
  10.     private StudentInterface studentInterface;
  11.     // 数据库的增(create)删(delete)改(update)查(read)操作分别对应 http 请求中的 POST,DELETE,PUT,GET
  12.     // 相应的 Mapping 注解有所不同
  13.     @GetMapping("/getAllStudents")
  14.     public List<Student> getAllStudents(){
  15.         return studentInterface.getAllStudents();
  16.     }
  17.     // 这里请求包含的参数用 REST 风格
  18.     @GetMapping("/findStudentById/{id}")
  19.     public Student findStudentById(@PathVariable("id")int id){
  20.         return studentInterface.findStudentById(id);
  21.     }
  22.     // 这里 add 和 update 的 student 由 Post 请求中的 JSON 解析而来,所以要加一个注解 @RequestBody
  23.     @PostMapping("/addNewStudent")
  24.     public void addNewStudent(@RequestBody Student student){
  25.         studentInterface.addNewStudent(student);
  26.     }
  27.     @PutMapping("/updateStudent")
  28.     public void updateStudent(@RequestBody Student student){
  29.         studentInterface.updateStudent(student);
  30.     }
  31.     @DeleteMapping("/deleteStudentById/{id}")
  32.     public void deleteStudentById(@PathVariable("id") int id){
  33.         studentInterface.deleteStudentById(id);
  34.     }
  35. }
复制代码
二、配置项目

在项目目次 main/resources 下新建目次 /Mapping ,用于存放配置 Mybatis 的配置文件
在 /Mapping 目次下新建配置文件 studentMap.xml :
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.busyforest.inter.StudentInterface">
  4.     <select id="getAllStudents" resultType="Student">
  5.         select * from student
  6.     </select>
  7.     <select id="findStudentById" parameterType="int" resultType="Student">
  8.         select * from student where id = #{id}
  9.     </select>
  10.     <insert id="addNewStudent" parameterType="Student">
  11.         insert into student values (#{id},#{name},#{major})
  12.     </insert>
  13.     <update id="updateStudent" parameterType="Student">
  14.         update student set name = #{name}, major = #{major} where id = #{id}
  15.     </update>
  16.     <delete id="deleteStudentById" parameterType="int">
  17.         delete from student where id = #{id}
  18.     </delete>
  19. </mapper>
复制代码
这个配置文件以 XML 的格式将 SQL 语句绑定到了相应的 java 接口方法中,同时规定了形参和返回值范例,便于框架中的转换器转换。
在项目目次 main/resources 下新建配置文件 application.yml (此处文件名为强制要求,不能更改)
  1. # 配置 Spring,连接到数据库
  2. spring:
  3.   datasource:
  4.     url: jdbc:mysql://localhost:3306/studentsql
  5.     username: root
  6.     password: 735568
  7.     driver-class-name: com.mysql.cj.jdbc.Driver
  8. # 配置 Mybatis,告诉框架配置文件的位置
  9. mybatis:
  10.   type-aliases-package: com.busyforest.entity
  11.   mapper-locations: classpath:/Mapping/studentMap.xml
复制代码
最后,在 com.busyforest 目次下新建主类 Main.java ,作为 Spring boot 应用的入口类:
  1. package com.busyforest;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. // @SpringBootApplication 表示该类是 Springboot 应用程序入口类
  6. // @MapperScan 是 Mybatis 的注解,用于把 com.busyforest.inter 中的实例化对象扫描到 IoC 容器中
  7. @SpringBootApplication
  8. @MapperScan("com.busyforest.inter")
  9. public class Main {
  10.     public static void main(String[] args) {
  11.         SpringApplication.run(Main.class,args);
  12.     }
  13. }
复制代码
运行 Main,控制台输出:

三、调试 CRUD 操纵

利用 postman 发送哀求,测试程序可否对数据库进行 CRUD 操纵。

需要将哀求范例设置为 POST,Body 添加 JSON 格式数据

POST 哀求没有返回值,但刷新数据库表可以发现已经添加乐成了:


至此,我们通过 Spring boot + Mybatis 完成了一个简单的数据库 CRUD 操纵程序。该程序接受 http 哀求,然后转化为对数据库的操纵,实现了基本的前后端分离。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4