目录
🚩三层架构
🎈JDBC操作回顾
🚩什么是MyBatis
MyBatis是一款优秀的 持久层 框架,用于简化JDBC的开发
🚩MyBatis⼊⻔
🎈准备工作
📝创建⼯程
创建springboot⼯程,并导⼊ mybatis的起步依赖、mysql的驱动包
项⽬⼯程创建完成后,⾃动在pom.xml⽂件中,导⼊Mybatis依赖和MySQL驱动依赖 。
<!--Mybatis 依赖包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
📝数据准备
创建⽤⼾表, 并创建对应的实体类User
-- 创建数据库
DROP DATABASE IF EXISTS mybatis_test;
CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;
-- 使⽤数据数据
USE mybatis_test;
-- 创建表[⽤⼾表]
DROP TABLE IF EXISTS userinfo;
CREATE TABLE `userinfo` (
`id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
`username` VARCHAR ( 127 ) NOT NULL,
`password` VARCHAR ( 127 ) NOT NULL,
`age` TINYINT ( 4 ) NOT NULL,
`gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-⼥ 0-默认',
`phone` VARCHAR ( 15 ) DEFAULT NULL,
`delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
`create_time` DATETIME DEFAULT now(),
`update_time` DATETIME DEFAULT now(),
PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
-- 添加⽤⼾信息
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'admin', 'admin', 18, 1, '18612340001' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );
创建对应的实体类 UserInfo
实体类的属性名与表中的字段名⼀⼀对应
package com.example.mybatis_test.model;
import lombok.Data;
import java.util.Date;
@Data
public class UserInfo {
private Integer id;
private String username;
private String password;
private Integer age;
private Integer gender;
private String phone;
private Integer deleteFlag;
private Date createTime;
private Date updateTime;
}
🎈配置数据库连接字符串
# 数据库连接配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
🎈写持久层代码
在项⽬中, 创建持久层接⼝UserInfoMapper2.
package com.example.mybatis_test.mapper;
import com.example.mybatis_test.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserInfoMapper2 {
//查询所有用户的信息
@Select("select * from userinfo")
List<UserInfo>getUserInfoAll();
}
🎈单元测试
在创建出来的SpringBoot⼯程中,在src下的test⽬录下,已经⾃动帮我们创建好了测试类 ,我们可以直接使⽤这个测试类来进⾏测试.
package com.example.mybatis_test.mapper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class UserInfoMapper2Test {
@Test
void getUserInfoAll() {
}
}
此时的测试单元类就自动生成了,再src/test/java/Mapper里面自动生成了测试类。
package com.example.mybatis_test.mapper;
import com.example.mybatis_test.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;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserInfoMapper2Test {
@Autowired
private UserInfoMapper2 userInfoMapper2;
@Test
void getUserInfoAll() {
List<UserInfo>userInfos=userInfoMapper2.getUserInfoAll();
for (UserInfo userInfo:userInfos) {
System.out.println(userInfo);
}
}
}
记得加 @SpringBootTest 注解, 加载Spring运⾏环境,否则会报错
测试类上添加了注解 @SpringBootTest,该测试类在运⾏时,就会⾃动加载Spring的运⾏环境.
我们通过@Autowired这个注解, 注⼊我们要测试的类, 就可以开始进⾏测试了 。
返回结果中, 可以看到, 只有SQL语句中查询的列对应的属性才有赋值。sql语句和查询的列属性不对应那么就默认为空值。
🚩MyBatis的基础操作
上⾯我们学习了Mybatis的查询操作, 接下来我们学习MyBatis的增, 删, 改操作 ,在学习这些操作之前, 我们先来学习MyBatis⽇志打印。
🎈打印日志
在Mybatis当中我们可以借助⽇志, 查看到sql语句的执⾏、执⾏传递的参数以及执⾏结果 ,在配置⽂件中进⾏配置即可。
#配置mybatis日志,为了后续观察sql语句的执行
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
我们看到,配置日志文件后,我们就可以观察到,sql语句的执行,以及执行结果,每一行都标注的清清楚楚,并且标注影响的行数。
🎈参数传递
需求: 查找id=4的⽤⼾,对应的SQL就是: select * from userinfo where id=4
//查询id=4的用户
@Select("select * from userinfo where id=#{id}")
UserInfo queryById(Integer id);
如果给where id=4表示只能查找id=4 的数据, 所以SQL语句中的id值不能写成固定数值,需要变为动态的数值 解决⽅案:在queryById⽅法中添加⼀个参数(id), 将⽅法中的参数,传给SQL语句
使⽤ #{} 的⽅式获取⽅法中的参数,使静态数据转成动态数据
如果mapper接⼝⽅法形参只有⼀个普通类型的参数,#{…} ⾥⾯的属性名可以随便写,如:#{id}、# {value}。 建议和参数名保持⼀致
🍭添加测试样例:
@Test
void queryById() {
UserInfo userInfo=userInfoMapper2.queryById(4);
System.out.println(userInfo);
}
🍭控制台结果
🎈增(Insert)
//增加一个用户
@Insert("insert into userinfo (username,`password`,age,gender) values" +
"(#{username},#{password},#{age},#{gender})")
Integer insert(UserInfo userInfo);
如果语句过长,我们可以直接敲回车,idea会自动给你换行。
🍭添加测试样例
@Test
void insert() {
UserInfo userInfo=new UserInfo();
userInfo.setUsername("zyf");
userInfo.setPassword("1005");
userInfo.setAge(20);
userInfo.setGender(1);
Integer count=userInfoMapper2.insert(userInfo);
System.out.println(count);
}
🍭控制台结果
📝返回主键(实现自增效果)
🎈删(delete)
📝使用注解:
@Delete("delete from userinfo where id=#{id}")
Integer delete(Integer id);
📝添加测试样例
此时的表中就删除了id=4的用户。
🎈改(Update)
📝使用注解
//更新一个用户的姓名
@Update("update userinfo set username=#{username} where id=#{id}")
Integer update(String username,Integer id);
📝添加测试样例
@Test
void update() {
Integer count=userInfoMapper2.update("zyf",5);
System.out.println(count);
}
🎈查(Select)
我们在上⾯查询时发现, 有⼏个字段是没有赋值的, 只有Java对象属性和数据库字段⼀模⼀样时, 才会进⾏赋值 ,接下来我们多查询⼀些数据
📝使用注解
@Select("select id, username, `password`, age, gender, phone, delete_flag, create_time, update_time from userinfo")
List<UserInfo> queryAllUser();
📝添加测试样例
@Test
void queryAllUser() {
List<UserInfo>infoList=userInfoMapper2.queryAllUser();
for (UserInfo userInfo:infoList) {
System.out.println(userInfo);
}
}
从运⾏结果上可以看到, 我们SQL语句中, 查询了delete_flag, create_time, update_time, 但是这⼏个属性却没有赋值.
📝起别名
在SQL语句中, 给列名起别名,保持别名和实体类属性名⼀样。
delete_flag as deleteFlag, create_time as createTime, update_time as updateTime
🍭使用注解
@Select("select id, username, `password`, age, gender, phone, delete_flag as deleteFlag, create_time as createTime, update_time as updateTime from userinfo")
List<UserInfo> queryAllUser2();
🍭添加测试
@Test
void queryAllUser2() {
List<UserInfo>infoList=userInfoMapper2.queryAllUser2();
for (UserInfo userInfo:infoList) {
System.out.println(userInfo);
}
}
📝结果映射
@Select("select id, username, `password`, age, gender, phone, delete_flag, create_time, update_time from userinfo")
@Results({
@Result(column = "delete_flag",property = "deleteFlag"),
@Result(column = "create_time",property = "createTime"),
@Result(column = "update_time",property = "updateTime")
})
List<UserInfo> queryAllUser();
如果其他SQL, 也希望可以复⽤这个映射关系, 可以给这个Results定义⼀个名,这样我们再queryById方法中我们要想得到id=4的用户,他查询之后的结果也是那三个属性不对应,我们就可以复用下面的@Results注解,用@RestultMap注解定位到@Results注解中id。
🍭测试结果
📝开启驼峰命名(推荐)
🍭配置驼峰自动转换
//查询所有用户的信息
@Select("select * from userinfo")
List<UserInfo>getUserInfoAll();
🍭添加测试样例
@Test
void getUserInfoAll() {
List<UserInfo>userInfos=userInfoMapper2.getUserInfoAll();
for (UserInfo userInfo:userInfos) {
System.out.println(userInfo);
}
}
相比于起别名和结果映射,开启驼峰命名更加的简单,只需要再配置文件中配置一下,即可。
🚩MyBatis XML配置文件
🎈配置连接字符串和MyBatis
此步骤需要进⾏两项设置,数据库连接字符串设置和 MyBatis 的 XML ⽂件配置。 如果是application.yml⽂件, 配置内容如下:
# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
mybatis:
mapper-locations: classpath:mapper/**Mapper.xml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
username: root
password: 105528clzyf.
driver-class-name: com.mysql.cj.jdbc.Driver
#配置mybatis日志,为了后续观察sql语句的执行
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
##配置驼峰⾃动转换
map-underscore-to-camel-case: true
# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
mapper-locations: classpath:mapper/UserInfoMapper2.xml
配置mybatis.xml文件,我们需要在src/main/resources/mapper目录下创建xml文件。
🎈写持久层代码
Interface用于方法定义,xxx.xml用于方法的实现,实现sql语句。
📝添加 mapper 接⼝
数据持久层的接⼝定义:
package com.example.mybatis_test.mapper;
import com.example.mybatis_test.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserInfoXmlMapper2 {
List<UserInfo>queryAllUser();
}
📝添加 UserInfoXMLMapper2.xml
数据持久成的实现,MyBatis 的固定 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.mybatis_test.mapper.UserInfoXmlMapper2">
</mapper>
创建UserInfoXMLMapper2.xml, 路径参考yml中的配置
# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
mapper-locations: classpath:mapper/UserInfoMapper2.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.mybatis_test.mapper.UserInfoXmlMapper2">
<select id="queryAllUser">
select username,`password`,age,gender,phone, from userinfo
</select>
</mapper>
📝单元测试
@SpringBootTest
class UserInfoMapper2Test {
@Autowired
private UserInfoMapper2 userInfoMapper2;
@Test
void getUserInfoAll() {
List<UserInfo>userInfos=userInfoMapper2.getUserInfoAll();
for (UserInfo userInfo:userInfos) {
System.out.println(userInfo);
}
}
}
🎈增删改查操作
📝增(Insert)
🍭UserInfoMapper2接⼝:
///增
Integer insertUser(UserInfo userInfo);
🍭UserInfoMapper.xml实现
<insert id="insertUser">
insert into userinfo (username,`password`,age,gender,phone)values (#{username},#{password},#{age},#{gender},#{phone})
</insert>
如果使⽤@Param设置参数名称的话, 使⽤⽅法和注解类似
🍭UserInfoMapper接⼝:
///增
Integer insertUser(@Param("userinfo") UserInfo userInfo);
🍭UserInfoMapper.xml实现:
<insert id="insertUser">
insert into userinfo (username,`password`,age,gender,phone)values (#{userinfo.username},#{userinfo.password},#{userinfo.age},#{userinfo.gender},#{userinfo.phone})
</insert>
返回⾃增 id
接⼝定义不变, Mapper.xml 实现 设置useGeneratedKeys 和keyProperty属性
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into userinfo (username,`password`,age,gender,phone)values (#{userinfo.username},#{userinfo.password},#{userinfo.age},#{userinfo.gender},#{userinfo.phone})
</insert>
📝删(Delete)
🍭UserInfoMapper接⼝
//删
Integer deleteUser(Integer id);
🍭UserInfoMapper.xml实现:
<delete id="deleteUser">
delete from userinfo where id=#{id};
</delete>
🍭测试
@Test
void deleteUser() {
Integer count=userInfoXmlMapper2.deleteUser(2);
System.out.println(count);
}
📝改(Update)
🍭UserInfoMapper接⼝
//改
Integer updateUser(String username,Integer id);
🍭UserInfoMapper.xml实现:
<update id="updateUser">
update userinfo set username=#{username} where id=#{id}
</update>
🍭测试
@Test
void updateUser() {
Integer count=userInfoXmlMapper2.updateUser("zzzzz",7);
System.out.println(count);
}
📝查(Select)
同样的, 使⽤XML 的⽅式进⾏查询, 也存在数据封装的问题 ,我们把SQL语句进⾏简单修改, 查询更多的字段内容
🍭UserInfoMapper接⼝
//查
List<UserInfo>selectUser();
🍭UserInfoMapper.xml实现:
<select id="selectUser">
select id, username,`password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo
</select>
🍭测试
@Test
void selectUser() {
List<UserInfo>infoList=userInfoXmlMapper2.selectUser();
for (UserInfo userInfo:infoList) {
System.out.println(userInfo);
}
}
结果显⽰: deleteFlag, createTime, updateTime 也没有进⾏赋值.
🍭结果映射
<resultMap id="BaseMap" type="com.example.mybatis_test.model.UserInfo">
<id column="id" property="id"></id>
<result column="delete_flag" property="deleteFlag"></result>
<result column="create_time" property="createTime"></result>
<result column="update_time" property="updateTime"></result>
</resultMap>
<select id="selectUser" resultMap="BaseMap">
select id, username,`password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo
</select>
注解方式和XML方式结果映射区别