1.MyBatis是什么?
(1)MyBatis是⼀款优秀的持久层框架,⽤于简化JDBC的开发。
--JDBC(Java DataBase Connectivity),即Java数据库连接。
(2)MyBatis本是 Apache的⼀个开源项⽬iBatis,2010年这个项⽬由apache迁移到了google code,并且改名为MyBatis 。2013年11⽉迁移到Github。(所以引包的时候ibatis和mybatis是一回事)
(3)持久层:指的就是持久化操作的层, 通常指数据访问层(dao), 是⽤来操作数据库的.
Dao和Mapper是数据层的
2.MyBatis的操作步骤
2.1 创建项目
(1)project type记得改为maven
(2)引包
Mybatis 是⼀个持久层框架, 具体的数据存储和数据操作还是在MySQL中操作的, 所以需要添加
MySQL驱动
(3)删掉不需要的文件
(4)更改相对应得包版本
并不需要记住对应的mybatis的版本,我们可以用edit starters直接导入。
2.2 数据准备
创建用户表, 并创建对应的实体类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' );
在ideal中创建对应的实体类 UserInfo
package com.example.demo.model;
import lombok.Data;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 吉祥瑞
* Date: 2024-03-23
* Time: 20:20
*/
@Data
//交由spring创造set和get语句
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;
}
2.3 配置数据库连接字符串
Mybatis中要连接数据库,需要数据库相关参数配置
• MySQL驱动类
• 登录名
• 密码
• 数据库连接字符串
如果是application.yml⽂件, 配置内容如下:
# 数据库连接配置
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
注意事项:
如果使用 MySQL 是 5.x 之前的使⽤的是"com.mysql.jdbc.Driver",如果是⼤于 5.x 使⽤的
是“com.mysql.cj.jdbc.Driver”.
2.4 写持久层代码
Mybatis的持久层接口规范⼀般都叫 XxxMapper
@Mapper注解:表示是MyBatis中的Mapper接⼝
• 程序运⾏时, 框架会自动⽣成接⼝的实现类对象(代理对象),并给交Spring的IOC容器管理
• @Select注解:代表的就是select查询,也就是注解对应⽅法的具体实现内容
2.4 单元测试
在创建出来的SpringBoot⼯程中,在src下的test⽬录下,已经⾃动帮我们创建好了测试类 ,我们可以直接使⽤这个测试类来进⾏测试.
(1)
package com.example.demo;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.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
class Mybatis03ApplicationTests {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
void contextLoads(){
List<UserInfo> userInfoMappers=userInfoMapper.queryAllUser();
System.out.println(userInfoMappers);
}
}
测试类上添加了注解 @SpringBootTest,该测试类在运⾏时,就会⾃动加载Spring的运⾏环境.
我们通过@Autowired这个注解, 注⼊我们要测试的类, 就可以开始进⾏测试了
(2)自动生成
选择要测试的⽅法, 点击 OK
package com.example.demo.mapper;
import com.example.demo.model.UserInfo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
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.*;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 吉祥瑞
* Date: 2024-03-23
* Time: 20:31
*/
@SpringBootTest
class UserInfoMapperTest {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
void queryAllUser() {
List<UserInfo> userInfos=userInfoMapper.queryAllUser();
System.out.println(userInfos);
}
}
结果:
记得加 @SpringBootTest 注解, 加载Spring运⾏环境
3.MyBatis的基础操作
3.1 打印日志
mybatis:
configuration: # 配置打印 MyBatis⽇志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
重新运⾏程序, 可以看到SQL执⾏内容, 以及传递参数和执⾏结果
①: 查询语句
②: 传递参数及类型
③: SQL执⾏结果
3.2 参数传递
@Select("select username, `password`, age, gender, phone from userinfo where id=#{id}}")
UserInfo queryById(Integer id);
@Test
void queryById() {
UserInfo userInfoss=userInfoMapper.queryById(4);
System.out.println(userInfoss);
}
3.3 增(Insert)
USE mybatis_test;
insert into userinfo (username, `password`, age, gender, phone) values ("zhaoliu","zhaoliu",19,1,"18700001234")
@Insert("insert into userinfo (username, `password`, age, gender, phone)
values (#{username},#{password},#{age},#{gender},#{phone})")
Integer insert(UserInfo userInfo);
测试代码
@Test
void insert() {
UserInfo userInfo=new UserInfo();
userInfo.setPassword("zhaoliu121");
userInfo.setGender(2);
userInfo.setAge(21);
userInfo.setUsername("www");
userInfo.setPhone("18612340005");
userInfoMapper.insert(userInfo);
}
成功
注意:
Insert 语句默认返回的是 受影响的⾏数
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert("insert into userinfo (username, age, gender, phone) values (#
{userinfo.username},#{userinfo.age},#{userinfo.gender},#{userinfo.phone})")
Integer insert(@Param("userinfo") UserInfo userInfo);
• useGeneratedKeys:这会令 MyBatis 使⽤ JDBC 的 getGeneratedKeys ⽅法来取出由数据库内
@Test
void insert12() {
UserInfo userInfo = new UserInfo();
userInfo.setUsername("zhaoliu");
userInfo.setPassword("zhaoliu");
userInfo.setGender(2);
userInfo.setAge(21);
userInfo.setPhone("18612340005");
Integer count = userInfoMapper.insert(userInfo);
Integer con=userInfo.getId();
System.out.println("添加数据条数:" +count +", 数据ID:" + con);
}
述 keyProperty 指定的属性中
3.4 删(Delete)
delete from userinfo where id=6
把SQL中的常量替换为动态的参数
Mapper接⼝
@Delete("delete from userinfo where id = #{id}")
void delete(Integer id);
3.5 改(Update)
update userinfo set username="zhaoliu" where id=5
@Update("update userinfo set username=#{username} where id=#{id}")
void update(UserInfo userInfo);
3.6 查(Select)
@Select("select id, username, `password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo")
List<UserInfo> queryAllUser();
注意:MyBatis 会根据⽅法的返回结果进⾏赋值.⽅法⽤对象 UserInfo接收返回结果, MySQL 查询出来数据为⼀条, 就会⾃动赋值给对象.⽅法⽤List<UserInfo>接收返回结果, MySQL 查询出来数据为⼀条或多条时, 也会⾃动赋值给List但如果MySQL 查询返回多条, 但是⽅法使⽤UserInfo接收, MyBatis执⾏就会报错.
名称一样自动赋值,名称不同需要找解决办法!!!
3.6.1 sql和java名称不同解决办法
3.6.1.1 起别名
@Select("select id, username, `password`, age, gender, phone, delete_flag as deleteFlag, " +
"create_time as createTime, update_time as updateTime from userinfo")
public List<UserInfo> queryAllUser2();
3.6.1.2 结果映射
@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> queryAllUser5();
如果其他SQL, 也希望可以复⽤这个映射关系, 可以给这个Results定义⼀个名称
@Select("select id, username, `password`, age, gender, phone, delete_flag, " +
"create_time, update_time from userinfo")
@Results(id = "resultMap",value = {
@Result(column = "delete_flag",property = "deleteFlag"),
@Result(column = "create_time",property = "createTime"),
@Result(column = "update_time",property = "updateTime")
})
List<UserInfo> queryAllUser6();
@Select("select id, username, `password`, age, gender, phone, delete_flag, " +
"create_time, update_time " +
"from userinfo where id= #{userid} ")
@ResultMap(value = "resultMap")
UserInfo queryById6(@Param("userid") Integer id);
利用id后面的resultmap进行复用
使⽤ id 属性给该 Results 定义别名, 使⽤ @ResultMap 注解来复⽤其他定义的 ResultMap
3.6.1.3 开启驼峰命名(推荐)
mybatis.configuration.map-underscore-to-camel-case=true #配置驼峰⾃动转换
驼峰命名规则: abc_xyz => abcXyz• 表中字段名:abc_xyz• 类中属性名:abcXyz
4. MyBatis XML配置⽂件
1. 注解2. XML
MyBatis XML的⽅式需要以下两步:1. 配置数据库连接字符串和MyBatis2. 写持久层代码
4.1 配置连接字符串和MyBatis
# 数据库连接配置
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
# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
mybatis:
mapper-locations: classpath:mapper/**Mapper.xml
4.2 写持久层代码
4.2.1 添加 mapper 接⼝
import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserInfoXMlMapper {
List<UserInfo> queryAllUser();
}
4.2.2 添加 UserInfoXMLMapper.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.demo.mapper.UserInfoXMlMapper">
</mapper>
查询所有⽤⼾的具体实现 :
<?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.UserInfoXMlMapper">
<select id="queryAllUser112" resultType="com.example.demo.model.UserInfo">
select username,password, age, gender, phone from userinfo
</select>
</mapper>
一一对应
package com.example.demo.mapper;
import com.example.demo.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;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 吉祥瑞
* Date: 2024-03-23
* Time: 22:23
*/
@SpringBootTest
public class UserInfoXMlMapperTest {
@Autowired
private UserInfoXMlMapper userInfoXMlMapper;
@Test
void queryAllUser() {
List<UserInfo> userInfoList = userInfoXMlMapper.queryAllUser112();
System.out.println(userInfoList);
}
}
4.3 增删改查操作
4.3.1 增(Insert)
<insert id="insertUser">
insert into userinfo (username, `password`, age, gender, phone) values (#
{username}, #{password}, #{age},#{gender},#{phone})
</insert>
4.3.2 删(Delete)
<delete id="deleteUser">
delete from userinfo where id = #{id}
</delete>
4.3.3 改(Update)
<update id="updateUser">
update userinfo set username=#{username} where id=#{id}
</update>
4.3.4 查(Select)
<select id="queryAllUser" resultType="com.example.demo.model.UserInfo">
select id, username,`password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo
</select>
同样有很多null
<resultMap id="BaseMap" type="com.example.demo.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="queryAllUser" resultMap="BaseMap">
select id, username,`password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo
</select>