一、理论储备
1、MyBatis 的概念
MyBatis 是比 JDBC 更简单的操作和读取数据库⼯具,它去除了繁琐的代码,通过简单的 XML 或 注解来配置和映射原始类型、接口和 Java POJO 为数据库记录。
2、MyBatis 的作用
对于后端开发来说,程序主要由两部分组成:后端程序 和 数据库。
我们依赖数据库连接工具,使得后端程序能够访问数据库,进行增删改查的操作。我们之前已经学习过一种工具(JDBC),但 JDBC 的操作太过繁琐了,MyBatis 更加简单。
回顾一下 JDBC 的流程:
- 创建数据库连接池 DataSource
- 通过 DataSource 获取数据库连接 Connection
- 编写要执⾏带 ? 占位符的 SQL 语句
- 通过 Connection 及 SQL 创建操作命令对象 Statement
- 替换占位符:指定要替换的数据库字段类型,占位符索引及要替换的值
- 使⽤ Statement 执⾏ SQL 语句
- 查询操作:返回结果集 ResultSet,更新操作:返回更新的数量
- 处理结果集
- 释放资源
二、第⼀个MyBatis查询
MyBatis 的组成:
- InterFace(接口):当前类的所有方法的声明
- XML:实现接口
MyBatis 也是⼀个 ORM 框架,ORM(Object Relational Mapping),即对象关系映射。在⾯向对象编程语⾔中,将关系型数据库中的数据与对象建⽴起映射关系,进⽽⾃动的完成数据与对象的互相转换:
- 将输⼊数据(即传⼊对象)+SQL 映射成原⽣ SQL
- 将结果集映射为返回对象,即输出对象
ORM 把数据库映射为对象:
- 数据库表(table)–> 类(class)
- 记录(record,⾏数据)–> 对象(object)
- 字段(field) --> 对象的属性(attribute)
⼀般的 ORM 框架,会将数据库模型的每张表都映射为⼀个 Java 类。
也就是说使⽤ MyBatis 可以像操作对象⼀样来操作数据库中的表,可以实现对象和数据库表之间
的转换
1、创建数据库和表
接下来我们要实现的功能是:使⽤ MyBatis 的⽅式来读取⽤户表中的所有⽤户,SQL如下:
-- 创建数据库
drop database if exists mycnblog;
create database mycnblog DEFAULT CHARACTER SET utf8mb4;
-- 使用数据数据
use mycnblog;
-- 创建表[用户表]
drop table if exists userinfo;
create table userinfo(
id int primary key auto_increment,
username varchar(100) not null,
password varchar(32) not null,
photo varchar(500) default '',
createtime datetime default now(),
updatetime datetime default now(),
`state` int default 1
) default charset 'utf8mb4';
-- 添加一个用户信息
INSERT INTO `mycnblog`.`userinfo` (`id`, `username`, `password`, `photo`, `createtime`, `updatetime`, `state`) VALUES
(1, 'admin', 'admin', '', '2021-12-06 17:10:48', '2021-12-06 17:10:48', 1);
2、添加MyBatis框架支持
添加 MyBatis 框架⽀持分为两种情况:
- 对⾃⼰之前的 Spring 项⽬进⾏升级;
- 创建⼀个全新的 MyBatis 和 Spring Boot 的项⽬。
① 老项目添加MyBatis
Ⅰ. 新增功能
在 pom.xml 文件中,直接增加框架支持:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
Ⅱ. EditStarters插件
在 pom.xml 文件中,鼠标右键 -> Generate -> EditStarters:增加 如下两个框架即可
② 新项目添加MyBatis
在创建时,直接添加框架即可:
3、配置连接字符串和MyBatis
① 配置连接字符串
在 application.yml 中添加如下内容:
# 数据库连接配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/mycnblog?characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
注意:
如果使⽤ mysql-connector-java 是 5.x 之前的使⽤的是“com.mysql.jdbc.Driver”,
如果是⼤于 5.x 使⽤的是“com.mysql.cj.jdbc.Driver”。
② 配置 MyBatis 中的 XML 路径
MyBatis 的 XML 中保存是查询数据库的具体操作 SQL,配置如下:
# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
mybatis:
mapper-locations: classpath:mapper/**Mapper.xml
configuration: # 配置打印 mybatis 执行的 SQL
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4、添加业务代码
① 添加实体类
创建一个与表对应的实体类:
代码如下:
package com.example.mybatisdemo.model;
import lombok.Data;
import java.util.Date;
/**
* 用户信息
* 普通的实体类,用于 MyBatis 做数据库表(userinfo)的映射
* 注意事项:标准类属性名称和 userinfo 表的字段完全一致()。
*/
@Data
public class UserInfo {
/**
* 用户id
*/
private Integer id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 电话号码
*/
private String photo;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 状态
*/
private Integer state;
}
② 添加 mapper 接口
创建一个与表对应的 mapper 接口:
代码如下:
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 使用 @Mapper,让接口变为 mybatis 的接口,不可忽略
*/
@Mapper
public interface UserInfoMapper {
/**
* 查询所有的信息
* @return
*/
public List<UserInfo> getAll();
/**
* 传参查询
* @param id
* @return
*/
public UserInfo getUserById(@Param("id")Integer id);
}
③ 添加 UserMapper.xml
在 resources 目录下的 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.example.mybatisdemo.mapper.UserInfoMapper">
<select id="getAll" resultType="com.example.mybatisdemo.model.UserInfo">
select * from userinfo
</select>
<select id="getUserById" resultType="com.example.mybatisdemo.model.UserInfo">
select * from userinfo where id=#{
id}
</select>
</mapper>
说明:
- < mapper>标签:
- namespace -> 实现的接口名(包名+类名)
- < select>标签:
- id -> 实现的方法名
- resultType -> 返回的数据类型(对应的实体类名)
- 在传参查询的时候,通过 #{id} 的方式来获取参数(此处的 id 与接口中的 @Param 注解所传 id 相同)
④ 测试
Ⅰ. 使用接口测试
a. 添加 Service
package com.example.mybatisdemo.service;
import com.example.mybatisdemo.mapper.UserInfoMapper;
import com.example.mybatisdemo.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserInfoService {
@Autowired
private UserInfoMapper userInfoMapper;
/**
* 查询所有的信息
* @return
*/
public List<UserInfo> getAll(){
return userInfoMapper.getAll();
}
/**
* 传参查询
* @param id
* @return
*/
public UserInfo getUserById(Integer id){
return userInfoMapper.getUserById(id);
}
}
b. 添加 Controller
package com.example.mybatisdemo.controller;
import com.example.mybatisdemo.model.UserInfo;
import com.example.mybatisdemo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@RestController
@RequestMapping("/userinfo")
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
/**
* 查询所有的信息
* @return
*/
@RequestMapping("/getAll")
public List<UserInfo> getAll() {
return userInfoService.getAll();
}
/**
* 传参查询
* @param id
* @return
*/
@RequestMapping("/getUserById")
public UserInfo getUserById(@RequestParam(value = "id", required = false) Integer id) {
return userInfoService.getUserById(id);
}
}
c. 使用 postman 测试
测试:http://localhost:8080/userinfo/getall
测试:http://localhost:8080/userinfo/getuserbyid?id=1
Ⅱ. 使用单元测试
在 Spring Boot 中,使用单元测试,教程链接:单元测试
测试类代码:
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest // 当前测试的上下文环境为 Spring Boot
class UserInfoMapperTest {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
void getAll() {
List<UserInfo> list = userInfoMapper.getAll();
for (UserInfo user : list) {
System.out.println(user.toString());
}
}
@Test
void getUserById() {
UserInfo userInfo = userInfoMapper.getUserById(1);
System.out.println(userInfo);
}
}
a. getAll 方法
b. getUserById 方法
三、增、删、改操作
1、准备工作
创建表:
-- 使用数据数据
use mycnblog;
-- 创建文章表
drop table if exists articleinfo;
create table articleinfo(
id int primary key auto_increment,
title varchar(100) not null,
content text not null,
createtime datetime default now(),
updatetime datetime default now(),
uid int not null,
rcount int not null default 1,
`state` int default 1
)default charset 'utf8mb4';
创建实体类:
package com.example.mybatisdemo.model;
import lombok.Data;
import java.util.Date;
/**
* 文章的实体类
*/
@Data
public class ArticleInfo {
/**
* 文章id
*/
private Integer id;
/**
* 标题
*/
private String title;
/**
* 正文
*/
private String content;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 发布文章的uid
*/
private Integer uid;
/**
* 访问量
*/
private Integer rcount;
/**
* 状态
*/
private Integer state;
}
2、增加用户操作
① 不使用 @Param
mapper 接口:
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.ArticleInfo;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArticleInfoMapper {
/**
* 添加方法
* @return
*/
public Integer add(ArticleInfo articleInfo);
}
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.example.mybatisdemo.mapper.ArticleInfoMapper">
<insert id="add">
insert into articleinfo(title, content, uid)
values (#{title}, #{content}, #{uid})
</insert>
</mapper>
单元测试代码为:
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.ArticleInfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit