MyBatis也是一个ORM框架,ORM即对象关系映射。在面向对象编程语言当中,讲关系型数据库中的数据与对象建立起映射关系,进行自动完成数据与对象的相互转换
- 将输入数据(即传入对象)+ SQL映射原生SQL
- 将结果集映射为返回对象,即输出对象
ORM把数据库映射为对象:
- 数据表—》 类
- 记录—》对象
- 字段—》对象的属性
一般的ORM框架,会将数据库模型的每一张表都映射为一个Java类
也就是说使用MyBatis可以像操作对象一样操作数据库中的表,可以实现对象和数据表之间的转换,我们接下来看看MyBatis的使用
4.1 创建数据库和表
使用MyBatis的方式来读取用户表当中的所有用户,我们使用个人博客的数据包。
-- 创建数据库
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';
-- 创建⽂章表
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';
-- 创建视频表
drop table if exists videoinfo;
create table videoinfo(
vid int primary key,
`title` varchar(250),
`url` varchar(1000),
createtime datetime default now(),
updatetime datetime default now(),
uid int
)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)
;
-- ⽂章添加测试数据
insert into articleinfo(title,content,uid)
values('Java','Java正⽂',1);
-- 添加视频
insert into videoinfo(vid,title,url,uid) values(1,'java title','http://ww
',1);4.2 添加MyBatis框架支持
添加MyBatis框架支持分为两种情况:一种情况是对之前的Spring项目进行升级,另一种情况是创建一个全新的MyBatis和Spring Boot项目
扩展:在老项目当中快速的添加框架,更简单的操作是使用EditStarters插件
4.3 配置连接字符串和MyBatis
此步骤需要进行两项设置,数据库连接字符串设置和MyBatis的XML文件配置
4.3.1 配置连接数据库
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mycnblog?characterEncoding=utf8&&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver注意事项:
如果使用mysql-connector-java是5.x之前使用的
con.mysql.jdbc.Driver如果大于5.x使用的是com.mysql.cj.jdbc.Driver
配置MyBatis中的XML路径
MyBatis的XML中保存的是查询数据库的具体操作的SQL,配置如下:
mybatis:
mapper-locations: classpath:mybatis/\*\*Mapper.xml4.4 添加业务代码
下面按照后端开发的工程思路,也就是下面的流程来实现MyBatis查询所有用户的功能:

4.4.1 添加实体类
先添加用户的实体类:
import lombok.Data;
import java.util.Date;
@Data
public class User {
private Integer id;
private String username;
private String password;
private String photo;
private Date createTime;
private Date updateTime;
}4.4.2 添加Mapper接口
数据持久层的接口定义:
@Mapper
public interface UserMapper {
public UserInfo getUserById(@Param("id") Integer id);
public void add(@RequestBody UserInfo userInfo);
}4.4.3 添加UserMapper.xml
数据持久层的实现,MyBatis的固定格式:
<?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.demo.mapper.UserMapper">
<select id="getUserById" resultType="com.example.demo.model.UserInfo">
select * from userinfo where id = #{id}
</select>
</mapper>- 标签:需要指定namespace属性,表示命名空间,值为mapper接口的全限定名,包括包名.类名
<select>标签:是用来执行数据库的查询操作的
- id:是和interface中定义的方法名称是一样的,表示对接口的具体实现方法
- resultType:是返回的数据类型,也就是开头定义的实体类
4.4.4 添加Service
服务层代码如下:
@Service
public class UserService {
@Resource
private UserMapper userMapper;
public UserInfo getUserById(Integer id) {
return userMapper.getUserById(id);
}
}4.4.5 添加Controller
控制层的代码实现如下:
@Controller
@ResponseBody
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/getuserbyid")
public UserInfo getUserById(Integer id) {
return userService.getUserById(id);
}
}5. 增、删、改操作
5.1 增加用户的操作
<insert id="add">
insert into userinfo(username, password, photo) values (#{username}, #{password}, #{photo})
</insert>
<insert id="getId" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into userinfo(username, password, photo) values (#{username}, #{password}, #{photo})
</insert>- useGeneratedKeys: 这会令MyBatis使用JDBC的getGeneratedKeys 方法取出由数据库内部生成的主键。(像MySQL和SQL service这样的关系型数据库关系系统自增主键)默认值是:false
- keyColumn: 设置生成建在表中的列名,在某些数据库当中,当主键的列不是第一列的时候,是必须设置的。如果生成列不止一个,可以用逗号分割各个属性名称
- keyProperty:指定能够唯一
5.2 删除用户的操作
<delete id="del">
delete from userinfo where id = #{id}
</delete>5.3 修改用户操作
<update id="update">
update userinfo set username = #{name} where id = #{id}
</update>6. 查询操作
6.1 单表查询
controller代码如下:
@RequestMapping("/getuserbyid")
public UserInfo getUserById(Integer id) {
return userService.getUserById(id);
}Mapper.xml实现代码如下:
<select id="getUserById" resultType="com.example.demo.model.UserInfo">
select * from userinfo where id = #{id}
</select>6.1.1 参数占位符 #{} 和 ${}
- #{} :预编译处理
- ${}:字符直接替换
预编译处理是指:MyBatis在处理#{}时,会将SQL中的#{}替换为?,使用statement的set方法来赋值。直接替换:是MyBatis在处理
时,就是把
{}时,就是把
时,就是把{}替换成变量的值
6.1.2 $优点
使用${}可以实现排序查询,而是用#{}就不能实现排序查询,因为当使用#{}查询时,如果传递的值为String则会加引号,就会导致SQL错误。
6.1.3 SQL 注入问题
<select id="isLogin" resultType="com.example.demo.model.User">
select * from userinfo where username='${name}' and password='${pwd}'
</select>结论:用于查询的字段,尽量使用#{}预查询的方式
6.1.4 like查询
like使用#{}报错,这个时候不能使用${},可以考虑使用MySQL内置的函数concat()来处理,实现代码如下:
<select id="findUserByName3" resultType="com.example.demo.model.User">
select * from userinfo where username like concat('%',#{username},'%');
</select>concat可以连接字符。
6.2 多表查询
如果增、删、改返回影响的行数,那么在mapper.xml中可以不设置返回的类型的。但是即使是最简单的查询,也要设置返回类型否则就会出现错误。
也就是说**对于<select>查询标签,至少存在两个属性:
- id 属性:用于标识实现接口的那个方法
- 结果映射属性:结果映射有两种实现标签:
<resultType和<resultMap
6.2.1 返回类型
绝大多数查询场景可以使用resultType进行返回,如下代码所示:
<select id="getNameById" resultType="java.lang.String">
select username from userinfo where id=#{id}
</select>它的优点就是使用方便、直接定义到某个实体类就可以
6.2.2 返回字典映射:resultMap
resultMap使用场景:
- 字段名称和程序中的属性名称不相同的情况,可以使用resultMap配置映射
- 一对一和多对一关系可以使用resultMap映射并查询数据
字段名和属性名不同的情况
<resultMap id="BaseMap" type="com.example.demo.model.User">
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="password" property="pwd"></result>
</resultMap>
<select id="getUserById" resultMap="com.example.demo.mapper.UserMapper.BaseMap">
select * from userinfo where id=#{id}
</select>6.2.3 多表查询
在多表查询的时候,如果使用resultMap标签,在一个类中包含了另一个对象是查询不出来包含的对象的。如下图所示:

此时我们就需要使用特殊手段来实现联表查询了。
6.2.3.1 一对一的映射
一对一映射要使用<association>标签,具体实现如下所示:一篇文章只能对应一个作者
<resultMap id="BaseMap" type="com.example.demo.model.ArticleInfo">
<id column="id" property="id"></id>
<result column="title" property="title"></result>
<result column="content" property="content"></result>
<result column="createtime" property="createtime"></result>
<result column="updatetime" property="updatetime"></result>
<result column="uid" property="uid"></result>
<result column="rcount" property="rcount"></result>
<result column="state" property="state"></result>
<association property="userInfo" resultMap="com.example.demo.mapper.UserMapper.BaseMap" columnPrefix="u\_"> </association>
</resultMap>
<select id="getArticleById" resultMap="BaseMap">
select a.*, u.id u_id, u.username u_username, u.password u_password from articleinfo a left join userinfo u on a.uid = u.id where = #{id}
</select>
















