前文:
(零)java前后端分离项目的相关应用准备
(一)后端项目的初始构建
前文我们介绍了一个Springboot后端项目的构建,本文将对Mysql数据库进行简单的增删改查操作。
1.建表
在对数据库操作前,我们得让数据库有数据。打开我们下载的navicat,连接自己的数据库后,建一张表,我这里就用学生表(student)举例,其拥有的字段如下:
- id:学号,唯一标识学生的key,int类型数据。
- name:姓名,varchar类型数据。
- gender:性别,0表女,1表男,bit类型数据。
- class_id:班级id,唯一,int类型数据。
- position_row:教室中的行位置,varchar类型数据。
- position_column:教室中的列位置,左边列小于右边列,varchar类型数据。
- teacher_id:班主任教师id,唯一,用于关联后续的教师表,int类型数据。
建表代码如下:
CREATE TABLE `student` (
`id` INT NOT NULL COMMENT '学号',
`name` VARCHAR ( 255 ) COLLATE utf8mb4_general_ci NOT NULL COMMENT '姓名',
`gender` bit ( 1 ) NOT NULL COMMENT '性别',
`class_id` INT DEFAULT NULL COMMENT '教室id',
`position_row` VARCHAR ( 255 ) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '座位行位置',
`position_column` VARCHAR ( 255 ) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '座位列位置',
`teacher_id` INT DEFAULT NULL COMMENT '班主任id',
PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci;
2.建基础数据类
在建基础数据类前,我们先引入MybatisPlus,它能使我们更为轻松的进行数据库的CURD。在我们主文件夹下的pom.xml文件内,标签内添加依赖,代码如下:
<!--Mybatis-Plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.3.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
刷新Maven,等待下载依赖完成。(注意,pom内若之前导入过Mybatis的依赖,需删除其后刷新Maven)
完成后,我们就需要在对应项目内建立与表字段一一对应的entity类,找到上次提前建的entity文件夹(src-main-java-com-test-common-entity
),新建一个StudentEntity类,并写上我们表内的各个数据项。具体代码如下:
package com.test.common.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @Author: 1399543132@qq.com
* @Date: 2024/01/21/20:16
* @Description: 学生表实体类
*/
@Data
@TableName("student")
public class StudentEntity {
/**
* 学号
*/
@TableId
private Long id;
/**
* 姓名
*/
private String name;
/**
* 性别
*/
private Integer gender;
/**
* 教室id
*/
private Long classId;
/**
* 行位置
*/
private String positionRow;
/**
* 列位置
*/
private String positionColumn;
/**
* 班主任id
*/
private Long teacherId;
}
- @Data注解为lombok内的一个好用的注解,其写在类上,能自动提供类的get、set、equals、hashCode、canEqual、toString方法,提高代码简洁性。
- @TableName为Mybatis-Plus的一个注解,能将该实体类和你所建的表关联起来。
- @TableId为Mybatis-Plus的一个注解,表主键的标识。
- Mybatis-plus和数据库表的映射规则是驼峰规则,如表内为class_id,对应的实体类内就应该为classId。
- 记得养成写注释的好习惯,IDEA内输入
/**
后回车,即可自动生成。
值得注意的是,我们controller内用的实体类并不是entity,而是dto,因此我们需要在dto文件夹内新建一个StudentDTO类,代码与StudentEntity一致,但只保留@Data注解,其余注解删除。
3.生成对基础数据类的Dao层操作方法
建完数据类后,我们还需要一些对其操作的方法,如增删改查等基础方法,幸运的是,Mybatis经帮我们把所有的方法都封装好了,我们直接用其注解即可。
我们先在common文件夹下再建一个dao文件夹,专门用于存放对实体类操作的interface。然后建立一个名为StudentDao的interface。
其内具体代码如下:
package com.test.common.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.common.entity.StudentEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* @Author: 1399543132@qq.com
* @Date: 2024/01/21/20:44
* @Description:
*/
@Mapper
public interface StudentDao extends BaseMapper<StudentEntity> {
}
- @Mapper是Mybatis的一个注解,能让我们进行简单的CURD操作时,不用去写复杂的xml文件(即数据库操作代码)。当然,涉及到复杂的表操作时,还是要去写xml。
- 继承的BaseMapper内即存有我们所需的增删改查操作方法,有兴趣的小伙伴可以自己按住ctrl点进去看看源码。
4.生成对基础数据类的Service层操作方法
虽然我们在第三步处已经生成了对数据的操作方法,但是其只涉及对数据库的访问,不涉及业务,我们将其称之为Dao层,而涉及业务的层次,我们称之为Service层,Service层调用Dao层的方法对数据库进行访问,而Controller层接收请求后则调用Service层的方法完成对应业务。
即: Controller----->Service------>Dao------>Entity(数据库)
因此,我们还需要编写Service层的方法,我们先在service文件夹下,建立一个StudentService的interface,表示增删改查的四个方法接口,其具体代码如下:
package com.test.common.service;
import com.test.common.dto.StudentDTO;
/**
* @Author: 1399543132@qq.com
* @Date: 2024/01/21/21:06
* @Description: 学生表相关Service接口
*/
public interface StudentService {
//增
Boolean addStudent(StudentDTO studentDTO);
//删
Boolean deleteStudentById(Long id);
//改
Boolean updateStudent(StudentDTO studentDTO);
//查
StudentDTO findStudentById(Long id);
}
接着我们在service-impl
文件夹下建立一个StudentServiceImpl类,实现StudentService内的四个接口,其代码如下:
package com.test.common.service.impl;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.test.common.dao.StudentDao;
import com.test.common.dto.StudentDTO;
import com.test.common.entity.StudentEntity;
import com.test.common.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @Author: 1399543132@qq.com
* @Date: 2024/01/21/21:14
* @Description:
*/
@Service
public class StudentServiceImpl implements StudentService {
@Resource
StudentDao studentDao;
@Override
public Boolean addStudent(StudentDTO studentDTO) {
//判定主键id是否为空,空则直接false
if(StrUtil.isNotEmpty(studentDTO.getId().toString())){
//dto转换为entity后插入
StudentEntity studentEntity = Convert.convert(StudentEntity.class,studentDTO);
return studentDao.insert(studentEntity) != 0;
}
return false;
}
@Override
public Boolean deleteStudentById(Long id) {
return studentDao.deleteById(id) != 0;
}
@Override
public Boolean updateStudent(StudentDTO studentDTO) {
StudentEntity studentEntity = studentDao.selectById(studentDTO.getId());
//不能查到对应entity,则插入
if(ObjectUtil.isEmpty(studentEntity)){
return this.addStudent(studentDTO);
}
return studentDao.updateById(Convert.convert(StudentEntity.class,studentDTO)) != 0;
}
@Override
public StudentDTO findStudentById(Long id) {
StudentEntity studentEntity = studentDao.selectById(id);
return Convert.convert(StudentDTO.class,studentEntity);
}
}
- 类上记得加@Service注解。
- 因为MybatisPlus自带的CURD操作返回为int,因此需转换为Boolean类型输出,添加 != 0判断。
- Convert.convert方法为hutool内的一个好用的类型转换方法。
5.编写接口
方法我们都有了后,就得开始写我们的接口了。在controller文件夹下建立一个StudentController类,用来接收外部的请求,其具体代码如下:
package com.test.common.controller;
import com.test.common.dto.StudentDTO;
import com.test.common.service.StudentService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @Author: 1399543132@qq.com
* @Date: 2024/01/21/21:37
* @Description: 学生表控制类
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService studentService;
@PostMapping("/add")
public Boolean addStudent(@RequestBody StudentDTO studentDTO){
return studentService.addStudent(studentDTO);
}
@GetMapping("/delete")
public Boolean deleteStudent(@RequestParam(value = "id") Long id){
return studentService.deleteStudentById(id);
}
@PostMapping("/update")
public Boolean updateStudent(@RequestBody StudentDTO studentDTO){
return studentService.updateStudent(studentDTO);
}
@GetMapping("/find")
public StudentDTO findStudent(@RequestParam(value = "id") Long id){
return studentService.findStudentById(id);
}
@GetMapping("/find/{id}")
public StudentDTO findStudent2(@PathVariable("id") Long id){
return studentService.findStudentById(id);
}
}
- 最后两个方法采用了不同的传参方式,一个是通过键值来传参,另一个是通过访问地址传参。
- 如果传的参数是@RequestBody ,多参或者传对象的情况下使用@PostMapping注解,同时,采用json格式传参。
- 无参,@RequestParam 和@PathVaiable的情况下使用@GetMapping注解,同时,采用form-data格式或地址传参。
接着…项目,启动!
耶?报错了,dao找不到,经过一番分析(百度),最终发现是在启动类上漏了@MapperScan注解,加上之后,顺利启动,启动类TestApplication代码如下:
package com;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Slf4j
@SpringBootApplication
@ServletComponentScan
@MapperScan({"com.test.common.dao"})
public class TestApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(TestApplication.class);
}
}
- 只是添加了一个@MapperScan注解,括号的内容是我们的dao所放的地方。
- 这里我自己有个疑惑,我查询资料,看到有人说dao上加上@Mapper即可不需要@MapperScan,但我依旧报错,不知为何,希望有小伙伴可以给我解答一下,万分感激。相关文档:mybatis-plus关于@Mapper、@Repository、@MapperScan、xml文件的相关问题_mapperscan pom-CSDN博客
6.接口测试
接口写完后,就要进行测试了。打开我们的Postman或者Apipost,输入对应的接口,再在下方的Body里面输入对应的json参数,即可进行接口测试。
Ⅰ、增
json参数如下:
{
"id":"1",
"name":"刻晴",
"gender":"0",
"classId":"1",
"positionRow":"1",
"positionColumn":"1",
"teacherId":"1"
}
结果如下图
Ⅱ、改
Ⅲ、查
Ⅳ、删(form-data格式传参)
至此,接口测试通过。
7、总结
这一篇文章,我们新建了一张学生表,还编写了entity、dto、dao、service、serviceImpl以及controller五个部分,运用Mybatis-plus实现了对这张学生表的基础增删改查操作,下一篇我们将扩展几张表,通过在xml文件内编写数据库语句,实现更为复杂的CURD,如连表查询等,以及通过运用JAVA 8的Lambda表达式对其进行简化。
8、参考文档
1.你知道什么时候用@PostMapping和@GetMapping吗?_啥时候使用getmpping和postmapping-CSDN博客
2.MyBatis-Plus 使用详解_mybatisplus用法-CSDN博客
3.MybatisPlus为什么可以不用@MapperScan_mapperscan 没写 也可以扫到-CSDN博客
4.mybatis-plus关于@Mapper、@Repository、@MapperScan、xml文件的相关问题_mapperscan pom-CSDN博客