《Mybatis基础》
目录
一、Mybatis简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的XML或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
Mybatis工作流程
- 加载配置文件(数据源、Mapper、Mapper.xml等),并将sql的配置信息加载成为一个个的MappedStatement对象,存储在内存中;
- 创建SqlSessionFactory;
- SqlSesisonFactory创建SqlSession,用于执行sql;
- 用户调用Mapper方法,映射至xml,解析sql后使用SqlSession注入数据库执行;
- 将返回的结果映射,封装成Java对象。
二、库表初始化
库表初始化
-- 选择数据库
use test;
-- teacher表初始化
drop table if exists teacher;
create table if not exists teacher(
teacher_id int primary key auto_increment comment '教师ID',
teacher_name varchar(20) not null comment '教师姓名',
age int comment '年龄',
phone_number char(11) unique comment '电话号码',
info varchar(300) default '暂无描述' comment '个人信息'
)comment '教师表';
insert into teacher values
(101,'A老师',25,'19938201920','人美声甜'),
(102,'B老师',30,'19938204430','帅气逼人'),
(103,'C老师',60,'19025103396','和蔼可亲');
-- student表初始化
drop table if exists student;
create table if not exists student(
student_id int primary key auto_increment comment '学生ID',
student_name varchar(20) comment '学生姓名',
chinese int comment '语文',
math int comment '数学',
english int comment '英语',
teacher_id int comment '班主任ID'
)comment '学生表';
-- 2.数据初始化
insert into student values
(1001,'Alice',80,90,100,101),
(1002,'Bob',60,70,80,101),
(1003,'Clover',95,90,80,101),
(1004,'Divid',85,90,100,102),
(1005,'Elen',80,70,40,102),
(1006,'French',80,80,80,109);
实体类
- com.hpr.entity.Teacher
...
@ApiModel("教师信息")
public class Teacher {
@ApiModelProperty("教师ID")
private int teacherId;
@ApiModelProperty("教师姓名")
private String teacherName;
@ApiModelProperty("年龄")
private int age;
@ApiModelProperty("电话号码")
private String phoneNumber;
@ApiModelProperty("个人信息")
private String info;
//无参构造
//set/get方法
//toString方法
...
}
- com.hpr.entity.Student
@ApiModel("学生信息")
public class Student {
@ApiModelProperty("学生ID")
private int studentId;
@ApiModelProperty("学生姓名")
private String studentName;
@ApiModelProperty("语文")
private int chinese;
@ApiModelProperty("数学")
private int math;
@ApiModelProperty("英语")
private int english;
@ApiModelProperty("班主任ID")
private int teacherId;
//无参构造
//set/get方法
//toString方法
...
}
三、Mybatis框架整合
- 资源文件夹创建
- pom.xml
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
- application.yml
spring:
#数据源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password: 123456
mybatis:
#xml扫描路径
mapper-locations: classpath:mappers/*Mapper.xml
configuration:
#日志打印
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- com.hpr.MainApplication
...
//mapper扫描的包位置
@MapperScan("com.hpr.mapper")
public class MainApplication {
...
}
- 启动测试
执行结果
四、Mybatis基本使用
- com.hpr.mapper.TeacherMapper
@Repository
public interface TeacherMapper {
List<Map<String, Object>> selectMaps();
}
- mappers/TeacherMapper.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.hpr.mapper.TeacherMapper">
<!-- resultType指定响应结果类型 -->
<select id="selectMaps" resultType="Map">
select * from teacher
</select>
</mapper>
- com.hpr.service.ITeacherService
public interface ITeacherService {
Response<List<Map<String,Object>>> selectMaps();
}
- com.hpr.service.impl.TeacherService
@Service
public class TeacherService implements ITeacherService {
@Autowired
private TeacherMapper teacherMapper;
@Override
public Response<List<Map<String, Object>>> selectMaps() {
return new Response<>(200, "success", teacherMapper.selectMaps());
}
}
- com.hpr.controller.MybatisController
@CrossOrigin("*")
@RestController
@RequestMapping("/mybatis")
@Api(tags = "Mybatis测试接口")
public class MybatisController {
@Autowired
private ITeacherService iTeacherService;
@GetMapping("/selectMaps")
@ApiOperation("查询教师信息列表(mapList)")
public Response<List<Map<String, Object>>> selectMaps() {
return iTeacherService.selectMaps();
}
}
- 启动测试
执行结果
总结
重点
- Mybatis工作流程;
- SSM框架整合;
- Mybatis代码书写。
难点
- Mybatis工作流程。