SpringBoot整合Mybatis进行crud操作
一:创建数据表
学生表
create table s_stu (
id int primary key auto_increment,
sname varchar(255),
age int,
sex char(1),
score double(10,2),
birthday date
);
教室表
create table s_classroom(
cid int primary key comment 'id',
cnum varchar(255) comment '教室编号',
seatNum int comment '座位数'
);
学科表
create table s_subject(
sub_id int primary key comment '学科id',
sub_name varchar(255) comment '学科名'
);
学生与学科的关联中间表
CREATE TABLE s_stu_sub (
sid int(11) NOT NULL COMMENT '学生id',
sub_id int(11) NOT NULL COMMENT '科目id',
PRIMARY KEY (`sid`,`sub_id`) -- 联合主键
);
老师表
create table s_teacher(
tid int primary key comment '老师id',
tname varchar(255) comment '老师名字',
tage int comment '老师年龄',
education varchar(255) comment '学历'
sub_id int comment '关联的学科id'
);
二:搭建SpringBoot环境
pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>Demo38_mybatis_curdDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Demo38_mybatis_curdDemo</name>
<description>Demo38_mybatis_curdDemo</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.example.Demo38MybatisCurdDemoApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
yml配置文件
# 连接数据库的信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: 1234
# 数据库连接池
type: com.alibaba.druid.pool.DruidDataSource
# mybatis配置
mybatis:
# 扫描映射文件
mapper-locations: classpath:mappers/*.xml
# 配置别名扫描的包
type-aliases-package: com.example.entity
configuration:
# 开启驼峰映射配置
map-underscore-to-camel-case: true
# 打印执行过程的sql信息
logging:
level:
com.example.mapper: DEBUG
创建实体类:以stu表为例
package com.example.entity;
import lombok.Data;
import java.sql.Date;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
@Data
public class Stu {
private Integer id;
private String sname;
private Integer age;
private String sex;
private Double score;
private Date birthday;
}
创建Mapper层
package com.example.mapper;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
public interface StuMapper {
}
创建Service层
package com.example.service;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
public interface StuService {
}
创建Service实现类
package com.example.service.impl;
import com.example.service.StuService;
import org.springframework.stereotype.Service;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
}
创建Controller层
package com.example.controller;
import com.example.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
@RestController
public class StuController {
@Autowired
private StuService stuService;
}
创建mapper配置文件
<?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.example.mapper.StuMapper">
</mapper>
修改启动类
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Demo38MybatisCurdDemoApplication {
public static void main(String[] args) {
SpringApplication.run(Demo38MybatisCurdDemoApplication.class, args);
}
}
创建一个工具类用来统一返回的数据格式
package com.example.utils;
/**
* @author zjc
* @date 2024/11/12
* @desc
*/
public class R {
private int code;
private String msg;
private Object data;
public static R fail() {
R r = new R();
r.setCode(4000);
r.setMsg("请求失败");
return r;
}
public static R fail(String msg) {
R r = new R();
r.setCode(4000);
r.setMsg(msg);
return r;
}
public static R ok() {
R r = new R();
r.setCode(2000);
r.setMsg("成功");
return r;
}
public static R ok(Object data) {
R r = new R();
r.setCode(2000);
r.setMsg("成功");
r.setData(data);
return r;
}
public static R ok(int code, String msg) {
R r = new R();
r.setCode(code);
r.setMsg(msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.setCode(2000);
r.setMsg(msg);
return r;
}
public static R ok(int code) {
R r = new R();
r.setCode(code);
r.setMsg("成功");
return r;
}
public R() {
}
public R(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
项目目录
三:实现功能(单表)
1.查询一个数据
根据ID查询学生信息
mapper接口
public interface StuMapper {
Stu findStuById(int id);
}
mapper配置文件
<?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.example.mapper.StuMapper">
<select id="findStuById" resultType="com.example.entity.Stu">
select *
from s_stu
where id = #{id}
</select>
</mapper>
service层
public interface StuService {
Stu findStuById(int id);
}
service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
@Override
public Stu findStuById(int id) {
return stuMapper.findStuById(id);
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
@GetMapping("/stu/findStuById")
public R findStuById(int id) {
Stu stu = stuService.findStuById(id);
return R.ok(stu);
}
}
使用postman测试
2.查询全部数据
mapper接口
public interface StuMapper {
// 查询全部数据
List<Stu> findAllStu();
}
mapper配置文件
<mapper namespace="com.example.mapper.StuMapper">
<select id="findAllStu" resultType="com.example.entity.Stu">
select *
from s_stu
</select>
</mapper>
service层
public interface StuService {
// 查询全部数据
List<Stu> findAllStu();
}
service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 查询全部数据
@Override
public List<Stu> findAllStu() {
return stuMapper.findAllStu();
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
@GetMapping("/stu/findAllStu")
public R findAllStu() {
List<Stu> allStu = stuService.findAllStu();
return R.ok(allStu);
}
}
测试
3.根据年龄或姓名查询学生
mapper接口
public interface StuMapper {
// 根据年龄或姓名查询学生
List<Stu> findStuByAgeOrName(HashMap<String,Object> map);
}
mapper配置文件
<mapper namespace="com.example.mapper.StuMapper">
<select id="findStuByAgeOrName" resultType="com.example.entity.Stu">
select * from s_stu
<where>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="sname != null and sanme != ''">
and sname like concat('%',#{sname},'%')
</if>
</where>
</select>
</mapper>
Student层
public interface StuService {
// 根据年龄或姓名查询学生
List<Stu> findStuByAgeOrName(HashMap<String, Object> map);
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 根据年龄或姓名查询学生
@Override
public List<Stu> findStuByAgeOrName(HashMap<String, Object> map) {
return stuMapper.findStuByAgeOrName(map);
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
@GetMapping("/stu/findStuByAgeOrName")
// 如果要接收集合类型,需要再参数前加上RequestParam注解
public R findStuByAgeOrName(@RequestParam HashMap<String, Object> map) {
List<Stu> stuList = stuService.findStuByAgeOrName(map);
return R.ok(stuList);
}
}
测试
4.添加数据
将实体类中日期类型的属性加上JsonFormat注解
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date birthday;
Mapper接口
public interface StuMapper {
// 添加数据
int addStu(Stu stu);
}
Mapper配置文件
<?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.example.mapper.StuMapper">
<insert id="addStu">
insert into s_stu(sname, age, sex, score, birthday)
values (#{sname}, #{age}, #{sex}, #{score}, #{birthday})
</insert>
</mapper>
Service层
public interface StuService {
// 添加数据
int addStu(Stu stu);
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
@Override
public int addStu(Stu stu) {
return stuMapper.addStu(stu);
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
@PostMapping("/stu/addStu")
public R addStu(Stu stu) {
int i = stuService.addStu(stu);
return R.ok(i);
}
}
测试
5.修改
Mapper接口
public interface StuMapper {
// 修改数据
int updateStu(Stu stu);
}
Mapper配置文件
<?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.example.mapper.StuMapper">
<update id="updateStu">
update s_stu
<set>
<if test="sname != null and sname != ''">
sname = #{sname},
</if>
<if test="age != null and age != ''">
age =#{age},
</if>
<if test="sex != null and sex != ''">
sex = #{sex},
</if>
<if test="score != null and score != ''">
score = #{score},
</if>
<if test="birthday != null">
birthday = #{birthday},
</if>
</set>
where id = #{id}
</update>
</mapper>
Service层
public interface StuService {
// 修改数据
int updateStu(Stu stu);
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 修改数据
@Override
public int updateStu(Stu stu) {
return stuMapper.updateStu(stu);
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
// 修改数据
@PostMapping("/stu/updateStu")
public R updateStu(Stu stu) {
int i = stuService.updateStu(stu);
return R.ok(i);
}
}
测试
6.删除
Mapper接口
public interface StuMapper {
// 删除数据
int deleteStuById(int id);
}
Mapper配置文件
<?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.example.mapper.StuMapper">
<delete id="deleteStuById">
delete
from s_stu
where id = #{id}
</delete>
</mapper>
Service层
public interface StuService {
// 删除数据
int deleteStuById(int id);
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 删除数据
@Override
public int deleteStuById(int id) {
return stuMapper.deleteStuById(id);
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
// 删除数据
@PostMapping("/stu/deteteStuById")
public R deleteStuById(int id) {
int i = stuService.deleteStuById(id);
return R.ok(i);
}
}
测试
7.批量删除
Mapper接口
public interface StuMapper {
// 批量删除
int batchDeleteStuById(ArrayList<Integer> ids);
}
Mapper配置文件
<?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.example.mapper.StuMapper">
<delete id="batchDeleteStuById">
delete from s_stu where id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
Service层
public interface StuService {
// 批量删除
int batchDeleteStuById(ArrayList<Integer> ids);
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 批量删除
@Override
public int batchDeleteStuById(ArrayList<Integer> ids) {
return stuMapper.batchDeleteStuById(ids);
}
}
Controller层
@RestController
public class StuController {
@Autowired
private StuService stuService;
// 批量删除
@PostMapping("/stu/batchDeleteStuById")
public R batchDeleteStuById(@RequestParam ArrayList<Integer> ids) {
int i = stuService.batchDeleteStuById(ids);
return R.ok(i);
}
}
测试
四:多表联查
1.一对一查询(两表)
查询学生以及关联的班级信息
学生和班级是一对一的关系
需要在学生表中添加一个cid列,用来和班级表关联
班级表
学生表
创建教室实体类
package com.example.entity;
import lombok.Data;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
@Data
public class ClassRoom {
private Integer cid;
private Integer cnum;
private Integer seatNum;
}
创建VO类用来接收封装查询结果
package com.example.vo;
import com.example.entity.ClassRoom;
import com.example.entity.Stu;
import lombok.Data;
/**
* @Author zjc
* @Date 2024/11/16
* @Desc
*/
@Data
public class StudentClassRoomVO extends Stu {
private ClassRoom classRoom;
}
Mapper接口
public interface StuMapper {
// 查询学生和班级对应信息
List<StudentClassRoomVO> findAllStudentClassRoom();
}
Mapper配置文件
使用ResultMap标签进行映射属性和字段对应关系
id的值自定义,type属性的值为查询结果类的全限类名
一对一使用association标签进行映射,其中property属性值为要关联的对象的属性值,javaType为数据类型
<?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.example.mapper.StuMapper">
<resultMap id="StudentClassRoom" type="com.example.vo.StudentClassRoomVO">
<id property="id" column="id"/>
<result property="sname" column="sname"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="score" column="score"/>
<result property="birthday" column="birthday"/>
<association property="classRoom" javaType="classRoom">
<id property="cid" column="cid"/>
<result property="cnum" column="cnum"/>
<result property="seatNum" column="seatNum"/>
</association>
</resultMap>
<select id="findAllStudentClassRoom" resultMap="StudentClassRoom">
select s.*, c.cnum, c.seatNum
from s_stu s,
s_classroom c
where s.cid = c.cid
</select>
</mapper>
Service层
public interface StuService {
// 查询学生和班级对应信息
List<StudentClassRoomVO> findAllStudentClassRoom();
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 查询学生和班级对应信息
@Override
public List<StudentClassRoomVO> findAllStudentClassRoom() {
return stuMapper.findAllStudentClassRoom();
}
}
Controller类
@RestController
public class StuController {
@Autowired
private StuService stuService;
// 查询学生和班级对应信息
@GetMapping("/stu/findAllStudentClassRoom")
public R findAllStudentClassRoom(){
List<StudentClassRoomVO> studentClassRoomList = stuService.findAllStudentClassRoom();
return R.ok(studentClassRoomList);
}
}
测试
查询结果
{
"code": 2000,
"msg": "成功",
"data": [
{
"id": 2,
"sname": "Sigewinne",
"age": 400,
"sex": "2",
"score": 99.0,
"birthday": "2023-11-01",
"cid": null,
"classRoom": {
"cid": 1,
"cnum": 1001,
"seatNum": 40
}
},
{
"id": 8,
"sname": "Nahida",
"age": 500,
"sex": "2",
"score": 100.0,
"birthday": "2023-11-05",
"cid": null,
"classRoom": {
"cid": 1,
"cnum": 1001,
"seatNum": 40
}
},
{
"id": 9,
"sname": "Tighnari",
"age": 22,
"sex": "1",
"score": 100.0,
"birthday": "2024-11-15",
"cid": null,
"classRoom": {
"cid": 2,
"cnum": 1002,
"seatNum": 42
}
},
{
"id": 10,
"sname": "Sethos",
"age": 21,
"sex": "1",
"score": 100.0,
"birthday": "2024-11-14",
"cid": null,
"classRoom": {
"cid": 3,
"cnum": 1003,
"seatNum": 43
}
}
]
}
2.一对多查询(两表)
查询某个学生以及学科信息
因为学生和学科是一对多的关系,所以需要中间表s_stu_sub,此表在开头已经创建完毕
中间表
学科表
在学生表中增加学科实体类的属性
private List<Subject> subjectList;
Mapper接口
public interface StuMapper {
// 查询某个学生以及学科信息
List<StudentClassRoomVO> findStuAndSubjectByStuId(Integer id);
}
Mapper配置文件
一对多需要使用Collection标签进行映射
其中property属性值为关联的对象的属性名字,ofType为集合中存储的数据类型,javaType为集合类型
<?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.example.mapper.StuMapper">
<resultMap id="StudentSubject" type="com.example.vo.StudentSubjectVO">
<id property="id" column="id"/>
<result property="sname" column="sname"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="score" column="score"/>
<result property="birthday" column="birthday"/>
<collection property="subjectList" ofType="com.example.entity.Subject" javaType="java.util.List">
<id property="subId" column="sub_id"/>
<result property="subName" column="sub_name"/>
</collection>
</resultMap>
<select id="findStuAndSubjectByStuId" resultMap="StudentSubject">
select s1.*, s2.*
from s_stu s1
left join s_stu_sub ss on s1.id = ss.sid
left join s_subject s2 on ss.sub_id = s2.sub_id
where s1.id = #{id}
</select>
</mapper>
Mapper接口
public interface StuMapper {
// 查询某个学生以及学科信息
List<StudentClassRoomVO> findStuAndSubjectByStuId(Integer id);
}
Service层
public interface StuService {
// 查询某个学生以及学科信息
List<StudentClassRoomVO> findStuAndSubjectByStuId(Integer id);
}
Service实现类
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper stuMapper;
// 查询某个学生以及学科信息
@Override
public List<StudentClassRoomVO> findStuAndSubjectByStuId(Integer id) {
return stuMapper.findStuAndSubjectByStuId(id);
}
}
Controller类
@RestController
public class StuController {
@Autowired
private StuService stuService;
// 查询某个学生以及学科信息
@GetMapping("/stu/findStuAndSubjectByStuId")
public R findStuAndSubjectByStuId(Integer id) {
return R.ok(stuService.findStuAndSubjectByStuId(id));
}
}
测试
测试结果
{
"code": 2000,
"msg": "成功",
"data": [
{
"id": 2,
"sname": "Sigewinne",
"age": 400,
"sex": "2",
"score": 99.0,
"birthday": "2023-11-01",
"cid": null,
"subjectList": [
{
"subId": 1,
"subName": "语文"
},
{
"subId": 2,
"subName": "数学"
},
{
"subId": 3,
"subName": "英语"
}
],
"subject": null
}
]
}
nts StuService {
@Autowired
private StuMapper stuMapper;
// 查询某个学生以及学科信息
@Override
public List findStuAndSubjectByStuId(Integer id) {
return stuMapper.findStuAndSubjectByStuId(id);
}
}
Controller类
```java
@RestController
public class StuController {
@Autowired
private StuService stuService;
// 查询某个学生以及学科信息
@GetMapping("/stu/findStuAndSubjectByStuId")
public R findStuAndSubjectByStuId(Integer id) {
return R.ok(stuService.findStuAndSubjectByStuId(id));
}
}
测试
测试结果
{
"code": 2000,
"msg": "成功",
"data": [
{
"id": 2,
"sname": "Sigewinne",
"age": 400,
"sex": "2",
"score": 99.0,
"birthday": "2023-11-01",
"cid": null,
"subjectList": [
{
"subId": 1,
"subName": "语文"
},
{
"subId": 2,
"subName": "数学"
},
{
"subId": 3,
"subName": "英语"
}
],
"subject": null
}
]
}
标签:SpringBoot,int,crud,private,public,stu,StuService,Mybatis,id
From: https://blog.csdn.net/qq_38930254/article/details/143819714