MyBatis【创建与使用】
- 🍎一. MyBatis
- 🍒1.1. MyBatis 是什么?
- 🍒1.2 没有使用MyBatis时的操作流程
- 🍒1.3 MyBatis的操作与数据库之间的流程
- 🍎二.创建MyBatis项目
- 🍒2.1 idea创建
- 🍒2.2 配置文件信息
- 🍉2.2.1 添加MySQL 驱动和MyBatis 框架
- 🍉2.2.2 配置数据库连接信息
- 🍉2.2.3 配置MyBaits在 application.xml保存路径
- 🍒2.3 创建数据库和表(文章表)
- 🍒2.4 创建对象
- 🍒2.5 创建Mapper接口
- 🍒2.6 在配置文件中配置UserMapper.xml文件
- 🍎三. MyBatis的使用
- 🍒3.1 添加 Service 和 controller
- 🍒3.2 在UserMapper.xml中进行SQL语句编写
- 🍒3.3 在postman进行访问查询
🍎一. MyBatis
🍒1.1. MyBatis 是什么?
MyBatis 是⼀款优秀的持久层框架
,它⽀持⾃定义 SQL、存储过程以及⾼级映射
。MyBatis 去除了⼏乎所有的 JDBC 代码以及设置参数和获取结果集的⼯作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接⼝和 Java POJO(Plain Old Java Objects,普通⽼式 Java 对象)为数据库中的记录
简单来说 MyBatis 是更简单完成程序和数据库交互的⼯具,也就是更简单的操作和读取数据库⼯具(中间商)
🍒1.2 没有使用MyBatis时的操作流程
这是因为 JDBC 的操作太繁琐了,我们回顾⼀下 JDBC 的操作流程:
- 创建数据库连接池
DataSource
- 通过 DataSource 获取数据库连接
Connection
- 编写要执⾏带
?
占位符的 SQL 语句 - 通过 Connection 及 SQL 创建操作命令对象
Statement
- 替换占位符:指定要替换的数据库字段类型,占位符索引及要替换的值
- 使⽤
Statement 执⾏ SQL
语句 查询操作:
返回结果集 ResultSet,更新操作:
返回更新的数量- 处理结果集
- 释放资源
从上述操作流程可以看出,对于 JDBC 来说,整个操作⾮常的繁琐,我们不但要拼接每⼀个参数,⽽且还要按照模板代码的⽅式,⼀步步的操作数据库,并且在每次操作完,还要⼿动关闭连接等,⽽所有的这些操作步骤都需要在每个⽅法中重复书写。于是我们就想,那有没有⼀种⽅法,可以更简单、更⽅便的操作数据库呢?答案是肯定的,这就是我们要学习 MyBatis 的真正原因,它可以帮助我们更⽅便、更快速的操作数据库’
🍒1.3 MyBatis的操作与数据库之间的流程
开始搭建 MyBatis 之前,我们先来看⼀下 MyBatis 在整个框架中的定位,框架交互流程图:
MyBatis 也是⼀个 ORM 框架,ORM(Object Relational Mapping),即对象关系映射。在⾯向对象编程语⾔中,将关系型数据库中的数据与对象建⽴起映射关系,进⽽⾃动的完成数据与对象的互相转换:
- 将输⼊数据(即传⼊对象)+SQL 映射成原⽣ SQL
- 将结果集映射为返回对象,即输出对象
ORM 把数据库映射为对象:
●数据库表(table)–> 类(class)
●记录(record,⾏数据)–> 对象(object)
●字段(field) --> 对象的属性(attribute)
●⼀般的 ORM 框架,会将数据库模型的每张表都映射为⼀个 Java 类
也就是说使⽤ MyBatis 可以像操作对象⼀样来操作数据库中的表,可以实现对象和数据库表之间的转换,接下来我们来看 MyBatis 的使⽤吧
🍎二.创建MyBatis项目
🍒2.1 idea创建
1.选择框架Spring Assistant框架(没有这个框架选择可以创建Spring的框架即可)
2.选择Maven项目和java的jdk版本
3.选择项目需要添加的依赖
🍒2.2 配置文件信息
🍉2.2.1 添加MySQL 驱动和MyBatis 框架
<!-- 添加 MyBatis 框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 添加 MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<scope>runtime</scope>
</dependency>
🍉2.2.2 配置数据库连接信息
# 开发环境配置文件
# 配置数据库连接
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mycnblog?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: jj1432644716
driver-class-name: com.mysql.cj.jdbc.Driver
# 开启 MyBatis SQL 打印
logging:
level:
com:
example:
demo: debug
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
在application.yml
输入以下代码在
# 当前运行的环境(配置文件)
spring:
profiles:
active: dev
🍉2.2.3 配置MyBaits在 application.xml保存路径
在application.yml
输入以下代码
# 配置 mybatis xml 保存路径 **Mapper.xml(是在**Mapper.xml后的文件名的目录下保存)
mybatis:
mapper-locations: classpath:mybatis/**Mapper.xml
🍒2.3 创建数据库和表(文章表)
-- 创建数据库
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';
-- 添加⼀个⽤户信息
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.4 创建对象
我们可以创建一个单独的包来存储对象model
创建一个用户对象,我们记得使用@Data注解(带有set,get,tostring等方法)
@Data
public class UserInfo {
private Integer id;
private String username;
private String password;
private String photo;
private String createtime;
private String updatetime;
private int state;
}
🍒2.5 创建Mapper接口
@Mapper //mybatis interface
public interface UserMapper {
}
我们先实现一个查询用户id的方法
Mapper //mybatis interface
public interface UserMapper {
// 查询方法{根据用户id查询用户}
// @Param("id")是mybatis中设置xml文件的SQL中查询id
public UserInfo getUserById(@Param("id") Integer id);
}
🍒2.6 在配置文件中配置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">
<!-- namepace 要设置是实现接口所在的具体包加类名 -->
<mapper namespace="com.example.demo.mapper.UserMapper">
🍎三. MyBatis的使用
🍒3.1 添加 Service 和 controller
1.添加 Service
@Service
public class UserService {
//属性注入
@Resource
private UserMapper userMapper;
public UserInfo getUserById(Integer id){
return userMapper.getUserById(id);
}
}
2.添加controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getuserbyid")
public UserInfo getUserById(Integer id) {
if (id == null) return null;
return userService.getUserById(id);
}
}
🍒3.2 在UserMapper.xml中进行SQL语句编写
<!-- 根据用户id 查询用户信息 -->
<select id="getUserById" resultMap="BaseMap">
select * from userinfo where id=#{id}
</select>
🍒3.3 在postman进行访问查询
这是我们创建后的项目目录