目录
- 1 MyBatis 概述
- 2 MyBatis 快速入门
- 3 Mapper 代理开发
- 4 配置文件实现CRUD
- 4.1 环境准备
- 4.2 查询所有数据
- 4.2.1 编写接口方法
- 4.2.2 编写 SQL 语句
- 4.2.3 编写测试方法
- 4.2.4 结果映射问题
 
- 4.3 查询详情
- 4.3.1 编写接口方法
- 4.3.2 编写SQL语句
- 4.3.3 编写测试方法
 
- 4.4 多条件查询
- 4.4.1 编写接口方法
- 4.4.2 编写SQL语句
- 4.4.3 编写测试方法
 
- 4.5 多条件动态查询
- 4.6 单条件动态查询
- 4.6.1 编写接口方法
- 4.6.2 编写SQL语句
- 4.6.3 编写测试方法
 
- 4.7 添加数据
- 4.7.1 编写接口方法
- 4.7.2 编写SQL语句
- 4.7.3 编写测试方法
 
- 4.8 修改全部字段
- 4.8.1 编写接口方法
- 4.8.2 编写SQL语句
- 4.8.3 编写测试方法
- 4.8.4 修改动态字段
 
- 4.9 删除一行数据
- 4.9.1 编写接口方法
- 4.9.2 编写SQL语句
- 4.9.3 编写测试方法
 
- 4.10 批量删除数据
- 4.10.1 编写接口方法
- 4.10.2 编写SQL语句
- 4.10.3 编写测试方法
 
- 4.11 MyBatis 参数传递
- 4.11.1 多个参数
- 4.11.2 单个参数
 
 
- 5 注解实现 CRUD
1 MyBatis 概述
MyBatis 本是 Apache 的一个开源项目 iBatis, 2010 年这个项目由 apache software
foundation 迁移到了 google code ,并且改名为 MyBatis 。 2013 年 11 月迁移到 Github。
MyBatis 是一款优秀的 持久层 框架,用于 简化 JDBC 开发。官方文档
- 持久层 
  - 负责将数据到保存到数据库的那一层代码
- JavaEE三层架构:表现层、业务层、持久层
 
- 框架 
  - 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
- 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
 
MyBatis 主要是用于简化 JDBC 开发,那么 JDBC 主要有哪些缺点呢?

那 MyBatis 又是如何简化 JDBC 开发的呢?

2 MyBatis 快速入门
查询 user 表中所有数据
- 创建 user 表,添加数据
- 创建模块,导入坐标
- 编写 MyBatis 核心配置文件 --> 替换连接信息 解决硬编码问
- 编写 SQL 映射文件 --> 统一管理 sql 语句,解决硬编码问题
- 编写代码 
  - 定义 POJO 类
- 加载核心配置文件,获取 SqlSessionFactory 对象
- 获取 SqlSession 对象,执行 SQL 语句
- 释放资源
 
示例代码
- 创建 user 表,添加数据
create database mybatis;
use mybatis;
drop table if exists tb_user;
create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);
INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
tb_user 表内容如下

- 创建模块 MyBatisDemo,导入坐标
如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中
    <dependencies>
        <!--MyBatis的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.13</version>
        </dependency>
        <!-- mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.5</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.4.7</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.4.7</version>
        </dependency>
    </dependencies>
另外,logback除了以上三个配置信息之外,还需要一个配置文件
logback.xml

- 编写 MyBatis 核心配置文件
在resources文件夹下新建配置文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <!--
    相当于给pojo下所有的实体类起了一个别名,而这个别名默认为实体类类名,不用带包名且不区分大小写
    这也就意味着,我们在 UserMapper.xml 中写返回结果类型 resultType 时,可以直接简化为 resultType="user"
    -->
    <typeAliases>
        <package name="com.huwei.pojo"/>
    </typeAliases>
    
    <!--MyBatis可以配置成适应多种环境,这种机制有助于将SQL映射于多种数据库之中,可以通过default属性切换不同的environment-->
  
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql的映射文件-->
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
注意,需要在下面配置 sql 映射文件
MyBatis 核心配置文件的顶层结构如下:

注意,在配置各个标签的时候,需要遵守前后顺序规则
- 编写 SQL 映射文件
在resources文件夹下新建配置文件 XxxMapper.xml ,这里数据表为用户表,则取名UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace:名称空间
resultType:返回结果的类型,即定义的 POJO 类 User类
-->
<mapper namespace="user">
    <!--
    查询语句
    id是这条sql语句的唯一标识,不能重复
    -->
     <!--<select id="selectAll" resultType="com.huwei.pojo.User">-->
    <select id="selectAll" resultType="user">
        select * from tb_user;
    </select>
</mapper>
- 编写代码
定义 POJO 类 User 类
package com.huwei.pojo;
public class User {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getAddr() {
        return addr;
    }
    public void setAddr(String addr) {
        this.addr = addr;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}
编写测试类文件 MyBatisDemo.java
package com.huwei;
import com.huwei.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisDemo {
    public static void main(String[] args) throws IOException {
        // 1. 加载核心配置文件,获取 SqlSessionFactory 对象
        String resource = "mybatis-config.xml"; // 该核心配置文件就在resource根目录下,直接写文件名就行
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2. 获取 SqlSession 对象,用它来执行 SQL 语句
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 执行sql语句(传入sql语句的唯一标识)
        List<User> users = sqlSession.selectList("user.selectAll");
        System.out.println(users);
        // 4. 释放资源
        sqlSession.close();
    }
}
解决 SQL 映射文件的警告提示
- 产生原因:IDEA和数据库没有建立连接,不识别表信息
- 解决方式:在IDEA中配置MySQL数据库连接

3 Mapper 代理开发
在第2小节 MyBatis 快速入门中,其实依然存在硬编码问题

而使用 Mapper 代理开发可以
- 解决原生方式中的硬编码
- 简化后期执行 SQL
使用 Mapper 代理方式完成入门案例
- 定义与 SQL 映射文件同名的 Mapper 接口,并且将 Mapper 接口和 SQL 映射文件放置在同一目录下
- 设置 SQL 映射文件的 namespace 属性为 Mapper 接口全限定名
- 在 Mapper 接口中定义方法,方法名就是 SQL 映射文件中 sql 语句的 id ,并保持参数类型和返回值类型一致
- 编码 
  - 通过 SqlSession 的 getMapper 方法获取 Mapper 接口的代理对象
- 调用对应方法完成 sql 的执行
 
示例代码:
- 定义与 SQL 映射文件同名的 Mapper 接口,并且将 Mapper 接口和 SQL 映射文件放置在同一目录下
在 resource文件夹下创建包(要和 Mapper 接口 所在的包名一致),注意,这里要使用/代代替.,创建完成后会变成 .,然后将 UserMapper.xml 拖入该包中

由于此步骤改变了UserMapper.xml的位置,我们还需要修改一下 mybatis-config.xml文件

注意:如果 Mapper 接口名称和 SQL 映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化 SQL 映射文件的加载

另外,我在使用 Maven编译时遇到了这个报错 Maven问题:【不支持源选项5。请使用7或更高版本。】
- 设置 SQL 映射文件的 namespace 属性为 Mapper 接口全限定名

- 在 Mapper 接口中定义方法,方法名就是 SQL 映射文件中 sql 语句的 id ,并保持参数类型和返回值类型一致
package com.huwei.mapper;
import com.huwei.pojo.User;
import java.util.List;
public interface UserMapper {
    List<User> selectAll();
}
- 编写代码
public class MyBatisDemo {
    public static void main(String[] args) throws IOException {
        // 1. 加载核心配置文件,获取 SqlSessionFactory 对象
        String resource = "mybatis-config.xml"; // 该核心配置文件就在resource根目录下,直接写文件名就行
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2. 获取 SqlSession 对象,用它来执行 SQL 语句
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        // 3. 执行sql语句(传入sql语句的唯一标识)
//        List<User> users = sqlSession.selectList("user.selectAll");
        // 3. 获取 UserMapper 接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectAll();
        System.out.println(users);
        // 4. 释放资源
        sqlSession.close();
    }
}
4 配置文件实现CRUD
如下图所示产品原型,里面包含了品牌数据的
查询、按条件查询、添加、删除、批量删除、修改等功能,而这些功能其实就是对数据库表中的数据进行CRUD操作。接下来我们就使用 Mybatis 完成品牌数据的增删改查操作。

总的来说,MyBatis 完成操作需要三步:编写接口方法 —> 编写 SQL —> 执行方法。
4.1 环境准备
- 数据表tb_brand和数据准备
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);
创建好的tb_brand表

- 在 com.huwei.pojo包下创建 Brand 实体类
package com.huwei.pojo;
public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;
    public Brand() {
    }
    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getBrandName() {
        return brandName;
    }
    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public Integer getOrdered() {
        return ordered;
    }
    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}
- 编写测试用例,测试代码需要在 test/java目录下创建包及测试用例。
项目结构如下:

- 安装 MyBatisX 插件
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。其主要功能:
- XML映射配置文件 和 接口方法 间相互跳转
- 根据接口方法生成 statement
安装方式
- 点击 file,选择settings,就能看到如下图所示界面

注意:安装完毕后需要重启IDEA
插件效果

红色头绳的表示映射配置文件,蓝色头绳的表示 mapper 接口。在 mapper 接口点击红色头绳的小鸟图标会自动跳转到对应的映射配置文件,在映射配置文件中点击蓝色头绳的小鸟图标会自动跳转到对应的 mapper 接口。
也可以在 mapper 接口中定义方法,自动生成映射配置文件中的 statement ,如图所示:

4.2 查询所有数据
4.2.1 编写接口方法
接口方法: Mapper 接口
- 参数:无
- 结果: List<Brand>
在 com.huwei.mapper 包写创建名为 BrandMapper 的接口。并在该接口中定义 List<Brand> selectAll() 方法
public interface BrandMapper {
    List<Brand> selectAll();
}
4.2.2 编写 SQL 语句
在 reources 下创建 com/huwei/mapper 目录结构,并在该目录下创建名为 BrandMapper.xml 的映射配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.huwei.mapper.BrandMapper">
    <select id="selectAll" resultType="brand">
        select *
        from tb_brand;
    </select>
</mapper>
4.2.3 编写测试方法
在 MybatisTest 类中编写测试查询所有的方法
@Test
public void testSelectAll() throws IOException {
    // 1. 加载核心配置文件,获取 SqlSessionFactory 对象
    String resource = "mybatis-config.xml"; // 该核心配置文件就在resource根目录下,直接写文件名就行
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 2. 获取 SqlSession 对象,用它来执行 SQL 语句
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 3. 获取 UserMapper 接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    // 4. 执行方法
    List<Brand> brands = mapper.selectAll();
    System.out.println(brands);
    // 5. 释放资源
    sqlSession.close();
}
注意:现在我们感觉测试这部分代码写起来特别麻烦,我们可以先忍忍。以后我们只会写上面的第3步的代码,其他的都不需要我们来完成。
执行测试方法结果如下:

4.2.4 结果映射问题
从上面结果我们看到了问题,有些数据封装成功了,而有些数据并没有封装成功。为什么这样呢?
从上面结果可以看到 brandName 和 companyName 这两个属性的数据没有封装成功,查询 实体类 和 表中的字段 发现,在实体类中属性名是 brandName 和 companyName ,而表中的字段名为 brand_name 和 company_name,如下图所示 。

那么我们只需要保持这两部分的名称一致这个问题就迎刃而解。
这个问题可以通过两种方式进行解决:
- 给字段起别名
- 使用 resultMap 定义字段和属性的映射关系
BrandMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.huwei.mapper.BrandMapper">
<!-- 数据库表的字段名称和实体类属性名称不一致,则不能自动封装数据
    <select id="selectAll" resultType="brand">
        select *
        from tb_brand;
    </select>-->
<!--
    1. 给字段起别名(方式一又有两种方式)
    1.1 对不一样的列名起别名,让别名和实体类的属性名一样(as也可以省略)
        缺点:每次查询都要定义一次别名
    <select id="selectAll" resultType="brand">
        select id,brand_name as brandName,company_name as companyName,ordered,description,status
        from tb_brand;
    </select>
    1.2 定义sql片段,提升复用性
        缺点:不够灵活
    <sql id="brand_column">
        select id,brand_name as brandName,company_name as companyName,ordered,description,status
    </sql>
    <select id="selectAll" resultType="brand">
        select
            <include refid="brand_column"></include>
        from tb_brand;
    </select>
     -->
    <!--
        2. resultMap(方式二可以分为两步)
            id:唯一标识
            type:映射的类型,支持别名
    -->
    <!--2.1 定义resultMap标签-->
    <resultMap id="brandResultMap" type="brand">
    <!--id:完成主键字段的映射
            column:表的列名
            property:实体类的属性名
        result:完成一般字段的映射
            column:表的列名
            property:实体类的属性名-->
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>
	<!--2.2 在select标签中使用resultMap属性代替resultType属性-->
    <select id="selectAll" resultMap="brandResultMap">
        select *
        from tb_brand;
    </select>
</mapper>
4.3 查询详情
有些数据的属性比较多,在页面表格中无法全部实现,而只会显示部分,而其他属性数据的查询可以通过 查看详情 来进行查询,如下图所示。

4.3.1 编写接口方法
Mapper接口
 - 参数:id
 - 查看详情就是查询某一行数据,所以需要根据 id 进行查询。而id以后是由页面传递过来。
 - 结果:Brand
 - 根据id查询出来的数据只要一条,而将一条数据封装成一个 Brand 对象即可
在 BrandMapper 接口中定义根据id查询数据的方法
/**
  * 查看详情:根据Id查询
  */
Brand selectById(int id);
4.3.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写 statement,使用 resultMap 而不是使用 resultType
<!--    
    <select id="selectById" parameterType="int" resultMap="brandResultMap">
    parameterType属性,用于设置参数的类型,可以省略不写
-->
<select id="selectById"  resultMap="brandResultMap">
    select *
    from tb_brand where id = #{id};
</select>
注意:
- 参数占位符
#{}:会将其替换为?,为了防止 SQL 注入
- 参数传递的时候使用
${}:字符串拼接SQL,会存在 SQL 注入问题
- 表名或列名不固定的时候,但是也会存在 SQL 注入问题
- 特殊字符处理(映射配置文件是 xml 类型的问题,而
><等这些字符在xml中有特殊含义,这里以<为例)
- 转义字符
- CDATA区(在IDEA中键入
CD回车)
4.3.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
@Test
public void testSelectById() throws IOException {
    // 接收参数
    int id=1;
    // 1. 加载核心配置文件,获取 SqlSessionFactory 对象
    String resource = "mybatis-config.xml"; // 该核心配置文件就在resource根目录下,直接写文件名就行
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 2. 获取 SqlSession 对象,用它来执行 SQL 语句
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 3. 获取 UserMapper 接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    // 4. 执行方法
    Brand brand = mapper.selectById(id);
    System.out.println(brand);
    // 5. 释放资源
    sqlSession.close();
}
执行测试方法结果如下:

4.4 多条件查询

我们经常会遇到如上图所示的多条件查询,将多条件查询的结果展示在下方的数据列表中。
条件字段 企业名称 和 品牌名称 需要进行模糊查询,所以条件应该是:

4.4.1 编写接口方法
在 BrandMapper 接口中定义多条件查询的方法
- 参数:所有查询条件
- 结果:List
而该功能有三个参数,我们就需要考虑定义接口时,参数应该如何定义。Mybatis针对多参数有多种实现:
- 散装参数:使用 @Param("参数名称")标记每一个参数,在映射配置文件中就需要使用#{参数名称}进行占位
List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName,@Param("brandName") String brandName);
- 对象参数:将多个参数封装成一个 实体对象 ,将该实体对象作为接口的方法参数。该方式要求在映射配置文件的SQL中使用 #{内容}时,里面的内容必须和实体类属性名保持一致。
List<Brand> selectByCondition(Brand brand);
- map集合参数:将多个参数封装到map集合中,将map集合作为接口的方法参数。该方式要求在映射配置文件的SQL中使用 #{内容}时,里面的内容必须和map集合中键的名称一致。
List<Brand> selectByCondition(Map map);
4.4.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写 statement,使用 resultMap 而不是使用 resultType
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    where status = #{status}
    and company_name like #{companyName}
    and brand_name like #{brandName}
</select>
注意:
like在没有使用通配符时等同于=操作符
4.4.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
@Test
public void testSelectByCondition() throws IOException {
    //接收参数
    int status = 1;
    String companyName = "华为";
    String brandName = "华为";
    // 处理参数
    companyName = "%" + companyName + "%";
    brandName = "%" + brandName + "%";
    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
	//方式一 :接口方法参数使用 @Param 方式调用的方法
    //List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
    //方式二 :接口方法参数是 实体类对象 方式调用的方法
     //封装对象
    /* Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);*/
    //List<Brand> brands = brandMapper.selectByCondition(brand);
    
    //方式三 :接口方法参数是 map集合对象 方式调用的方法
    Map map = new HashMap();
    map.put("status" , status);
    map.put("companyName", companyName);
    map.put("brandName" , brandName);
    List<Brand> brands = brandMapper.selectByCondition(map);
    System.out.println(brands);
    //5. 释放资源
    sqlSession.close();
}
上述功能实现存在很大的问题。因为用户在输入条件时,很可能不会所有的条件都填写
例如,我们只输入 brandName,就会出现如下情况

4.5 多条件动态查询
SQL 语句会随着用户输入或外部条件的变化而变化,我们称为 动态SQL。
而 Mybatis 对动态SQL有很强大的支撑:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
在 BrandMapper.xml 映射配置文件修改 SQL 语句
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    where
        <if test="status != null">
            status = #{status}
        </if>
        <!--if是用来条件判断的,test属性里面写逻辑表达式,注意在这里and or 不能替换成&& ||-->
        <if test="companyName != null and companyName != '' ">
            and company_name like #{companyName}
        </if>
        <if test="brandName != null and brandName != '' ">
            and brand_name like #{brandName}
        </if>
</select>
如上的这种SQL语句就会根据传递的参数值进行动态的拼接。如果此时 status 和companyName 有值那么就会值拼接这两个条件。
执行结果如下:

但是它也存在问题,如果此时给的参数值是
Map map = new HashMap();
// map.put("status" , status);
map.put("companyName", companyName);
map.put("brandName" , brandName);
拼接的SQL语句就变成了
select * from tb_brand where and company_name like ? and brand_name like ?
而上面的语句中 where 关键后直接跟 and 关键字,这就是一条错误的SQL语句。
可以通过恒等式解决
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    <!--恒等式-->
    where 1=1
    <if test="status != null">
        and status = #{status}
    </if>
    <!--test属性里面写逻辑表达式,注意在这里and or 不能替换成&& ||-->
    <if test="companyName != null and companyName != '' ">
        and company_name like #{companyName}
    </if>
    <if test="brandName != null and brandName != '' ">
        and brand_name like #{brandName}
    </if>
</select>
这个问题,我们也可以通过 where 标签解决
where 标签的作用:
- 替换 where关键字
- 会动态的去掉第一个条件前的 and
- 如果所有的参数没有值则不加 where关键字
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    <where>
        <if test="status != null">
            status = #{status}
        </if>
        <if test="companyName != null and companyName != '' ">
            and company_name like #{companyName}
        </if>
        <if test="brandName != null and brandName != '' ">
            and brand_name like #{brandName}
        </if>
    </where>
</select>
4.6 单条件动态查询

如上图所示,在查询时只能选择 品牌名称、当前状态、企业名称 这三个条件中的一个,但是用户到底选择哪儿一个,我们并不能确定。这种就属于单个条件的动态SQL语句。
这种需求需要使用到 choose(when,otherwise)标签 实现, 而 choose 标签类似于Java 中的 switch 语句。
4.6.1 编写接口方法
在 BrandMapper 接口中定义单条件查询的方法
4.6.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写 statement,使用 resultMap 而不是使用 resultType
<select id="selectByConditionSingle" resultMap="brandResultMap">
    select *
    from tb_brand
    <where>
        <choose> <!--相当于switch-->
            <when test="status != null"> <!--相当于case-->
                status = #{status}
            </when>
            <when test="companyName != null and companyName != '' "> <!--相当于case-->
                company_name like #{companyName}
            </when>
            <when test="brandName != null and brandName != ''"> <!--相当于case-->
                brand_name like #{brandName}
            </when>
            <!--<otherwise> 如果不使用where标签进行动态调整SQL,也可以使用otherwise标签,otherwise就相当于default
            	1=1 
            </otherwise>-->
        </choose>
    </where>
</select>
4.6.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
@Test
public void testSelectByConditionSingle() throws IOException {
    //接收参数
    int status = 1;
    String companyName = "华为";
    String brandName = "华为";
    // 处理参数
    companyName = "%" + companyName + "%";
    brandName = "%" + brandName + "%";
    //封装对象
    Brand brand = new Brand();
    //brand.setStatus(status);
    brand.setCompanyName(companyName);
    //brand.setBrandName(brandName);
    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    List<Brand> brands = brandMapper.selectByConditionSingle(brand);
    System.out.println(brands);
    //5. 释放资源
    sqlSession.close();
}
4.7 添加数据
4.7.1 编写接口方法
在 BrandMapper 接口中定义添加方法
void add(Brand brand);
4.7.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写添加数据的 statement
<insert id="add">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
4.7.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
@Test
public void testAdd() throws IOException {
    //接收参数
    int status = 1;
    String companyName = "波导手机";
    String brandName = "波导";
    String description = "手机中的战斗机";
    int ordered = 100;
    //封装对象
    Brand brand = new Brand();
    brand.setStatus(status);
    brand.setCompanyName(companyName);
    brand.setBrandName(brandName);
    brand.setDescription(description);
    brand.setOrdered(ordered);
    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true); //设置自动提交事务,这种情况不需要手动提交事务了
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    brandMapper.add(brand);
    //可以发现我们获取不到添加数据的id 
    //Integer id =brand.getId();
    //System.out.println(id); // null
    
    //提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}
在数据添加成功后,有时候需要获取插入数据库数据的主键(主键是自增长),即 主键返回。但是像上述代码那样直接打印主键,是获取不到主键值的。
我们将上面添加品牌数据的案例中 BrandMapper.xml 映射配置文件里 statement 进行修改,如下
<insert id="add" useGeneratedKeys="true" keyProperty="id">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
在 insert 标签上添加如下属性:
useGeneratedKeys:是够获取自动增长的主键值。true表示获取
keyProperty:指定将获取到的主键值封装到实体类的哪儿个属性里
4.8 修改全部字段
4.8.1 编写接口方法
在 BrandMapper 接口中定义修改方法
int update(Brand brand); // 返回影响的数据行数
上述方法参数 Brand 就是封装了需要修改的数据,而id肯定是有数据的,这也是和添加方法的区别
4.8.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写修改数据的 statement
<update id="update">
    update tb_brand
    set brand_name = #{brandName},
        company_name = #{companyName},
        ordered = #{ordered},
        description = #{description},
        status = #{status}
    where id = #{id};
</update>
4.8.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
@Test
public void testUpdate() throws IOException {
    //接收参数
    int status = 1;
    String companyName = "vivo";
    String brandName = "vivo手机";
    String description = "真好使";
    int ordered = 200;
    int id =5;
    //封装对象
    Brand brand = new Brand();
    brand.setStatus(status);
    brand.setCompanyName(companyName);
    brand.setBrandName(brandName);
    brand.setDescription(description);
    brand.setOrdered(ordered);
    brand.setId(id);
    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    int cnt = brandMapper.update(brand);
    System.out.println(cnt);
    //提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}
4.8.4 修改动态字段
比如我们只修改 status的值,修改 MybatisTest类中 的测试方法
	//封装对象
    Brand brand = new Brand();
    brand.setStatus(status);
    //brand.setCompanyName(companyName);
    //brand.setBrandName(brandName);
    //brand.setDescription(description);
    //brand.setOrdered(ordered);
    brand.setId(id);
运行结果如下:

在 BrandMapper.xml 映射配置文件中做如下修改
<update id="update">
    update tb_brand
    <set>
        <if test="brandName != null and brandName != ''">
            brand_name = #{brandName},
        </if>
        <if test="companyName != null and companyName != ''">
            company_name = #{companyName},
        </if>
        <if test="ordered != null">
            ordered = #{ordered},
        </if>
        <if test="description != null and description != ''">
            description = #{description},
        </if>
        <if test="status != null">
            status = #{status}
        </if>
    </set>
    where id = #{id};
</update>
执行测试方法结果如下:

从结果中SQL语句可以看出,只修改了 status 字段值,因为我们给的数据中只给Brand实体对象的 status 属性设置值了。这就是 set 标签的作用。
set标签可以用于动态包含需要更新的列,忽略其它不更新的列。
4.9 删除一行数据
4.9.1 编写接口方法
在 BrandMapper 接口中定义根据id删除方法
void deleteById(int id);
4.9.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写删除一行数据的 statement
<delete id="deleteById">
    delete from tb_brand where id = #{id};
</delete>
4.9.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
 @Test
public void testDeleteById() throws IOException {
    //接收参数
    int id = 6;
    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    brandMapper.deleteById(id);
    //提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}
4.10 批量删除数据
4.10.1 编写接口方法
在 BrandMapper 接口中定义删除多行数据的方法。
void deleteByIds(int[] ids);
// void deleteByIds(@Param(ids) int[] ids); // 可以通过 @Param 改变对应map里key的名称为ids
参数是一个数组,数组中存储的是多条数据的 id
4.10.2 编写SQL语句
在 BrandMapper.xml 映射配置文件中编写删除多条数据的 statement。
编写SQL时需要遍历数组来拼接SQL语句。Mybatis 提供了 foreach 标签供我们使用
 ,用来迭代任何可迭代的对象(如数组,集合)。
- collection 属性:mybatis会将数组参数,封装为一个Map集合。 
  - 默认:array = 数组
- 使用@Param注解改变map集合的默认key的名称
 
- 默认:
- item 属性:本次迭代获取到的元素。
- separator 属性:集合项迭代之间的分隔符。foreach标签不会错误地添加多余的分隔符。也就是最后一次迭代不会加分隔符。
- open 属性:该属性值是在拼接SQL语句之前拼接的语句,只会拼接一次
- close 属性:该属性值是在拼接SQL语句拼接后拼接的语句,只会拼接一次
<delete id="deleteByIds">
    delete from tb_brand where id
    in
    <foreach collection="array" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
    ;
</delete>
假如数组中的 id 数据是 {1,2,3} ,那么拼接后的 sql 语句就是:
delete from tb_brand where id in (1,2,3);
4.10.3 编写测试方法
在 test/java 下的 com.huwei.mapper 包下的 MybatisTest类中 定义测试方法
@Test
public void testDeleteByIds() throws IOException {
    //接收参数
    int[] ids = {5,7,8};
    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    brandMapper.deleteByIds(ids);
    //提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}
4.11 MyBatis 参数传递
Mybatis 接口方法中可以接收各种各样的参数,如下:
- 多个参数
- 单个参数:单个参数又可以是如下类型 
  - POJO 类型
- Map 集合类型
- Collection 集合类型
- List 集合类型
- Array 类型
- 其他类型
 
4.11.1 多个参数
如下面的代码,就是接收两个参数,而接收多个参数需要使用 @Param 注解,那么为什么要加该注解呢?这个问题要弄明白就必须来研究Mybatis 底层对于这些参数是如何处理的。
User select(@Param("username") String username,@Param("password") String password);
<select id="select" resultType="user">
	select *
    from tb_user
    where 
    	username=#{username}
    	and password=#{password}
</select>
我们在接口方法中定义多个参数,Mybatis 会将这些参数封装成 Map 集合对象,值就是参数值,而键在没有使用 @Param 注解时有以下命名规则:
- 以 arg开头 :第一个参数就叫arg0,第二个参数就叫arg1,以此类推。如:- map.put("arg0",参数值1);
- map.put("arg1",参数值2);
 
- 以 param开头 : 第一个参数就叫param1,第二个参数就叫param2,依次类推。如:- map.put("param1",参数值1);
- map.put("param2",参数值2);
 
示例代码
在 UserMapper 接口中定义如下方法
User select(String username,String password);
在 UserMapper.xml 映射配置文件中定义SQL
<select id="select" resultType="user">
	select *
    from tb_user
    where 
    	username=#{arg0}
    	and password=#{arg1}
</select>
或者
<select id="select" resultType="user">
	select *
    from tb_user
    where 
    	username=#{param1}
    	and password=#{param2}
</select>
运行代码结果如下

在映射配合文件的SQL语句中使用用 arg 开头的和 param 书写,代码的可读性会变的特别差,此时可以使用 @Param 注解。
以后接口参数是多个时,在每个参数上都使用 @Param 注解。这样代码的可读性更高。
4.11.2 单个参数
- POJO 类型 
  - 直接使用。要求 属性名和参数占位符名称一致
 
- 直接使用。要求 
- Map 集合类型 
  - 直接使用。要求 map集合的键名和参数占位符名称一致
 
- 直接使用。要求 
- Collection 集合类型 
  - Mybatis 会将集合封装到 map 集合中,如下: 
    - map.put("arg0",collection集合);
- map.put("collection",collection集合);
 
 
- Mybatis 会将集合封装到 map 集合中,如下: 
    
- List 集合类型 
  - Mybatis 会将集合封装到 map 集合中,如下: 
    - map.put("arg0",list集合);
- map.put("collection",list集合);
- map.put("list",list集合);
 
 
- Mybatis 会将集合封装到 map 集合中,如下: 
    
- Array 类型 
  - Mybatis 会将集合封装到 map 集合中,如下: 
    - map.put("arg0",数组);
- map.put("array",数组);
 
 
- Mybatis 会将集合封装到 map 集合中,如下: 
    
- 其他类型 
  - 比如int类型,参数占位符名称叫什么都可以。尽量做到见名知意
 
- 比如int类型,
5 注解实现 CRUD
使用注解开发会比配置文件开发更加方便。如下就是使用注解进行开发
@Select(value = "select * from tb_user where id = #{id}")
public User select(int id);
注解是用来替换映射配置文件方式配置的,所以使用了注解,就不需要再映射配置文件中书写对应的
statement
Mybatis 针对 CURD 操作都提供了对应的注解,已经做到见名知意。如下:
- 查询 :@Select
- 添加 :@Insert
- 修改 :@Update
- 删除 :@Delete
使用示例
将之前案例中 UserMapper.xml 中的 根据id查询数据 的 statement 注释掉

在 UserMapper 接口的 selectById 方法上添加注解

运行测试程序也能正常查询到数据
如何选择?
- 注解完成简单功能,配置文件完成复杂功能




















