首页 > 数据库 >02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发

时间:2023-06-08 22:35:55浏览次数:46  
标签:02 mapper 插件 配置文件 brand sqlSession status SQL id



文章目录

  • Mybatis CRUD练习
  • 1,配置文件实现CRUD
  • 1.1 环境准备
  • Debug01: 别名mybatisx报错
  • 1.2 查询所有数据
  • 1.2.1 编写接口方法
  • 1.2.2 编写SQL语句
  • 1.2.3 编写测试方法
  • 1.2.4 起别名解决上述问题
  • 1.2.5 使用resultMap解决上述问题
  • 1.2.6 小结
  • 1.3 查询详情
  • 1.3.1 编写接口方法
  • 1.3.2 编写SQL语句
  • 1.3.3 编写测试方法
  • 1.3.4 参数占位符
  • 1.3.5 parameterType使用
  • 1.3.6 SQL语句中特殊字段处理
  • 小结:
  • 1.4 多条件查询 ★(参数接收方式)
  • 1.4.1 编写接口方法
  • 1.4.2 编写SQL语句
  • 1.4.3 编写测试方法
  • 小结
  • 1.4.4 动态SQL ★
  • 1.5 单个条件(动态SQL)
  • 1.5.1 编写接口方法
  • 1.5.2 编写SQL语句
  • 1.5.3 编写测试方法
  • -----------------------Mybatis配置文件增删改---------------------------
  • 1.6 添加数据
  • 1.6.1 编写接口方法
  • 1.6.2 编写SQL语句
  • 1.6.3 编写测试方法
  • 1.6.4 添加-主键返回
  • 1.7 修改
  • 1.7.1 编写接口方法
  • --------修改全部字段--------
  • 1.7.2 编写SQL语句
  • 1.7.3 编写测试方法
  • --------动态修改部分字段--------
  • 1.7.2 编写SQL语句
  • 1.7.3 编写测试方法
  • 1.8 删除一行数据
  • 1.8.1 编写接口方法
  • 1.8.2 编写SQL语句
  • 1.8.3 编写测试方法
  • 1.9 批量删除
  • 1.9.1 编写接口方法
  • 1.9.2 编写SQL语句 (foreach 标签)
  • 1.9.3 编写测试方法
  • 1.10 Mybatis参数传递
  • 1.10.1 多个参数
  • ==结论:以后接口参数是多个时,在每个参数上都使用 `@Param` 注解。这样代码的可读性更高。★==
  • 1.10.2 单个参数 (各种集合类型的默认key参数,但是不建议使用默认key)
  • ==可以使用 `@Param` 注解替换map集合中默认的 arg 键名。建议【Collection、List、Array 、前面的多个参数】 都这么使用,增强可读性==
  • 2,注解实现CRUD (简单查询神器)
  • 2.1 注解查询@Select
  • 2.4 注解添加@Insert
  • 2.3 注解修改@Update
  • 2.2 注解删除@Delete
  • 2.3 结果集映射
  • 2.4 小结


Mybatis CRUD练习

目标

  • 能够使用映射配置文件实现CRUD操作
  • 能够使用注解实现CRUD操作

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java

1,配置文件实现CRUD

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_02

如上图所示产品原型,里面包含了品牌数据的 查询按条件查询添加删除批量删除修改 等功能,而这些功能其实就是对数据库表中的数据进行CRUD操作。接下来我们就使用Mybatis完成品牌数据的增删改查操作。以下是我们要完成功能列表:

  • 查询
  • 查询所有数据
  • 查询详情
  • 条件查询
  • 添加
  • 修改
  • 修改全部字段
  • 修改动态字段
  • 删除
  • 删除一个
  • 批量删除

我们先将必要的环境准备一下。

1.1 环境准备

完全继承上面的环境,接着做

  • 数据库表(tb_brand)及数据准备
-- mybatis数据库下
use mybatis;
-- 删除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);
  • 实体类 Brand
    cn.whu.pojo 包下创建 Brand 实体类。
    这里体会到 自动导包真的太爽了
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;
}
  • 编写测试用例
    测试代码需要在 test/java 目录下创建包及测试用例。项目结构如下:
  • 安装 MyBatisX 插件
  • MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
  • 主要功能
  • XML映射配置文件 和 接口方法 间相互跳转
  • 根据接口方法生成 statement (就是sql映射配置)
  • 安装方式
    点击 file ,选择 settings ,就能看到如下图所示界面

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_sql_03

注意:旧版本安装完毕后可能需要重启IDEA 新版IDEA不需要

  • 插件效果

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_04

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

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_SQL_05


02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_sql_06

Debug01: 别名mybatisx报错

问题: mybatisx插件自动生成的statement配置,resultType默认是全路径名,并未使用别名,如果强制使用别名会报错,单并不影响运行,就是看着烦
解决: 直接alter+enter -> disabled ins… 忽略掉即可 不影响程序运行的

1.2 查询所有数据

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_sql_07

如上图所示就页面上展示的数据,而这些数据需要从数据库进行查询。接下来我们就来讲查询所有数据功能,而实现该功能我们分以下步骤进行实现:

  • 编写接口方法:Mapper接口
  • 参数:无
    查询所有数据功能是不需要根据任何条件进行查询的,所以此方法不需要参数。
  • 结果:List
    我们会将查询出来的每一条数据封装成一个 Brand 对象,而多条数据封装多个 Brand 对象,需要将这些对象封装到List集合中返回。
  • 执行方法、测试

1.2.1 编写接口方法

cn.whu.mapper 包写创建名为 BrandMapper 的接口。并在该接口中定义 List<Brand> selectAll() 方法。

public interface BrandMapper {

    /**
     * 查询所有
     */
    List<Brand> selectAll();
}

1.2.2 编写SQL语句

reources 下创建 cn/whu/mapper 目录结构,并在该目录下创建名为 BrandMapper.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="cn.whu.mapper.BrandMapper">
    <select id="selectAll" resultType="brand">
        select *
        from tb_brand;
    </select>
</mapper>

1.2.3 编写测试方法

MybatisTest 类中编写测试查询所有的方法
cn.whu.test.MybatisTest

@Test
public void testSelectAll() throws Exception {
    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4. 执行方法
    List<Brand> brands = mapper.selectAll();
    System.out.println(brands);

    //5. 释放资源
    sqlSession.close();
}

注意:现在我们感觉测试这部分代码写起来特别麻烦,我们可以先忍忍。以后我们只会写上面的第3步的代码,其他的都不需要我们来完成。

执行测试方法结果如下:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_08

从上面结果我们看到了问题,有些数据封装成功了,而有些数据并没有封装成功。为什么这样呢?

这个问题可以通过两种方式进行解决:

  • 给字段起别名
  • 使用resultMap定义字段和属性的映射关系

1.2.4 起别名解决上述问题

从上面结果可以看到 brandNamecompanyName 这两个属性的数据没有封装成功,查询 实体类 和 表中的字段 发现,在实体类中属性名是 brandNamecompanyName ,而表中的字段名为 brand_namecompany_name,如下图所示 。那么我们只需要保持这两部分的名称一致这个问题就迎刃而解。

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_09

我们可以在写sql语句时给这两个字段起别名,将别名定义成和属性名一致即可。

<select id="selectAll" resultType="brand">
    select
    id, brand_name as brandName, company_name as companyName, ordered, description, status
    from tb_brand;
</select>

而上面的SQL语句中的字段列表书写麻烦,如果表中还有更多的字段,同时其他的功能也需要查询这些字段时就显得我们的代码不够精炼。Mybatis提供了sql 片段可以提高sql的复用性。

SQL片段:

  • 将需要复用的SQL片段抽取到 sql 标签中
<sql id="brand_column">
	id, brand_name as brandName, company_name as companyName, ordered, description, status
</sql>

id属性值是唯一标识,引用时也是通过该值进行引用。

  • 在原sql语句中进行引用
    使用 include 标签引用上述的 SQL 片段,而 refid 指定上述 SQL 片段的id值。
<select id="selectAll" resultType="brand">
    select
    <include refid="brand_column" />
    from tb_brand;
</select>

最终配置:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_10

1.2.5 使用resultMap解决上述问题

起别名 + sql片段的方式可以解决上述问题,但是它也存在问题。如果还有功能只需要查询部分字段,而不是查询所有字段,那么我们就需要再定义一个 SQL 片段,这就显得不是那么灵活。

那么我们也可以使用resultMap来定义字段和属性的映射关系的方式解决上述问题。

  • 在映射配置文件中使用resultMap定义 字段 和 属性 的映射关系
<!--id: 唯一标识 随便取名  type:指的是哪个pojo的映射 支持别名-->
    <!--
        <id></id> 映射主键的
            column: 表的列名
            property: 实体类的属性名
        <result></result> 映射其他一般字段的
    -->
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>

    </resultMap>

注意:在上面只需要定义 字段名 和 属性名 不一样的映射,而一样的则不需要专门定义出来

  • SQL语句正常编写
    在<select>标签中,使用resultMap属性替换 resultType属性
<select id="selectAll" resultMap="brandResultMap">
    select *
    from tb_brand;
</select>

最终BrandMapper.xml

<mapper namespace="cn.whu.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

    <select id="selectAll" resultMap="brandResultMap">
        select *
        from tb_brand;
    </select>
</mapper>

1.2.6 小结

实体类属性名 和 数据库表列名 不一致,不能自动封装数据

  • 起别名 : 在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样
  • 可以定义 片段,提升复用性
  • resultMap :定义 完成不一致的属性名和列名的映射

而我们最终选择使用 resultMap的方式。查询映射配置文件中查询所有的 statement 书写如下:

<resultMap id="brandResultMap" type="brand">
     <!--
            id:完成主键字段的映射
                column:表的列名
                property:实体类的属性名
            result:完成一般字段的映射
                column:表的列名
                property:实体类的属性名
        -->
     <result column="brand_name" property="brandName"/>
     <result column="company_name" property="companyName"/>
</resultMap>



<select id="selectAll" resultMap="brandResultMap">
    select *
    from tb_brand;
</select>

1.3 查询详情

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_11

有些数据的属性比较多,在页面表格中无法全部实现,而只会显示部分,而其他属性数据的查询可以通过 查看详情 来进行查询,如上图所示。

查看详情功能实现步骤:

  • 编写接口方法:Mapper接口
  • 参数:id
    查看详情就是查询某一行数据,所以需要根据id进行查询。而id以后是由页面传递过来。
  • 结果:Brand
    根据id查询出来的数据只要一条,而将一条数据封装成一个Brand对象即可
  • 编写SQL语句:SQL映射文件
  • 执行方法、进行测试

1.3.1 编写接口方法

BrandMapper 接口中定义根据id查询数据的方法

/**
  * 查看详情:根据Id查询
  */
Brand selectById(int id);

1.3.2 编写SQL语句

BrandMapper.xml 映射配置文件中编写 statement,使用 resultMap 而不是使用 resultType

<select id="selectById"  resultMap="brandResultMap">
    select *
    from tb_brand where id = #{id};
</select>

注意:上述SQL中的 #{id}先这样写,一会我们再详细讲解

1.3.3 编写测试方法

test/java 下的 cn.whu.test 包下的 MybatisTest类中 定义测试方法
cn.whu.test.MybatisTest

@Test
    public void testSelectById() throws Exception {
        // 接收参数
        int id = 1;

        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 执行方法
        Brand brand = mapper.selectById(id);
        System.out.println(brand);

        //5. 释放资源
        sqlSession.close();
    }

执行测试方法结果如下:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_12

1.3.4 参数占位符

查询到的结果很好理解就是id为1的这行数据。而这里我们需要看控制台显示的SQL语句,能看到使用?进行占位。说明我们在映射配置文件中的写的 #{id} 最终会被?进行占位。接下来我们就聊聊映射配置文件中的参数占位符。

mybatis提供了两种参数占位符:

  • #{} :执行SQL时,会将 #{} 占位符替换为?,将来自动设置参数值。从上述例子可以看出使用#{} 底层使用的是 PreparedStatement ★ (JDBC学了 知道了预编译 就很好理解了 )
  • ${} :拼接SQL。底层使用的是 Statement,会存在SQL注入问题。如下图将 映射配置文件中的 #{} 替换成 ${} 来看效果
<select id="selectById"  resultMap="brandResultMap">
    select *
    from tb_brand where id = ${id};
</select>

重新运行查看结果如下:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_13

注意 : 从上面两个例子可以看出,以后开发我们使用 #{} 参数占位符。

* 参数占位符:
           1. #{}: 会将其替换为 ?, 为了防止SQL注入
           2. ${}: 拼sql, 会存在SQL注入问题
           3. 使用时机:
                * 参数传递的时候: #{}
               【 * 表名或者列名不固定的情况下: ${} 会存在SQL注入问题  】 (了解即可 基本不用)

1.3.5 parameterType使用

对于有参数的mapper接口方法,我们在映射配置文件中应该配置 ParameterType 来指定参数类型。只不过该属性都可以省略如下图:

<select id="selectById" parameterType="int" resultMap="brandResultMap">
    select *
    from tb_brand where id = ${id};
</select>

parameterType=“int” 不用写了 真好。接口方法里已经有了,然后调用的时候传什么就赋什么就行了
(单个简单类型(int,couble,string等)的占位符随便写)

1.3.6 SQL语句中特殊字段处理

以后肯定会在SQL语句中写一下特殊字符,比如某一个字段大于某个值,如下图

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_SQL_14

可以看出报错了,因为映射配置文件是xml类型的问题,而 > < 等这些字符在xml中有特殊含义,所以此时我们需要将这些符号进行转义,可以使用以下两种方式进行转义

  • 转义字符
    下图的 &lt; 就是 < 的转义字符。

小结:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_15

1.4 多条件查询 ★(参数接收方式)

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_16

我们经常会遇到如上图所示的多条件查询,将多条件查询的结果展示在下方的数据列表中。而我们做这个功能需要分析最终的SQL语句应该是什么样,思考两个问题

  • 条件表达式
  • 如何连接

条件字段 企业名称品牌名称 需要进行模糊查询,所以条件应该是:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_17

简单的分析后,我们来看功能实现的步骤:

  • 编写接口方法
  • 参数:所有查询条件
  • 结果:List
  • 在映射配置文件中编写SQL语句
  • 编写测试方法并执行

1.4.1 编写接口方法

BrandMapper 接口中定义多条件查询的方法。

而该功能有三个参数,我们就需要考虑定义接口时,参数应该如何定义。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集合作为接口的方法参数。该方式要求在映射配置文件的SQL中使用 #{内容} 时,里面的内容必须和map集合中键的名称一致。
List<Brand> selectByCondition(Map map);

1.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>

1.4.3 编写测试方法

test/java 下的 cn.whu.test 包下的 MybatisTest类中 定义测试方法
cn.whu.test.MybatisTest

  • 方式:1:散装参数

散装参数: 如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称(就是#{}内的名称)”)

@Test
public void testSelectByCondition() throws Exception {
    // 接收参数
    int status = 1;
    String companyName = "华为";
    String brandName = "华为";

    //处理参数
    companyName = "%" + companyName + "%";
    brandName = "%" + brandName + "%";

    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4. 执行方法
    List<Brand> brands = mapper.selectByCondition(status, companyName, brandName);
    System.out.println(brands);

    //5. 释放资源
    sqlSession.close();
}
  • 方式2:对象参数

对象参数: 对象的属性名称要和参数占位符名称一致
(前面的test方法得注释了 否则编译不过)

@Test
public void testSelectByCondition2() throws Exception {
    // 接收参数
    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
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4. 执行方法
    List<Brand> brands = mapper.selectByCondition(brand);
    System.out.println(brands);

    //5. 释放资源
    sqlSession.close();
}
  • 方式3:map集合参数

map的key值映射文件sql语句里的占位符保持一致 说明: #{占位符}

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_SQL_18

@Test
public void testSelectByCondition3() throws Exception {
    // 接收参数
    int status = 1;
    String companyName = "华为";
    String brandName = "华为";

    //处理参数
    companyName = "%" + companyName + "%";
    brandName = "%" + brandName + "%";

    // 参数封装成对象
    Map map = new HashMap();//值类型是变的 所以不能有范型
    map.put("status",status);//key和映射sql里的占位符保持一致     说明: #{占位符}
    map.put("companyName",companyName);
    map.put("brandName",brandName);

    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4. 执行方法
    List<Brand> brands = mapper.selectByCondition(map);
    System.out.println(brands);

    //5. 释放资源
    sqlSession.close();
}

文件编码改成UTF-8 否则中文字符识别不了。(这样会导致日志里面出现乱码,没得办法了)
运行结果和sql语句都是偶尔们想要的

[DEBUG] 17:02:01.435 [main] c.w.m.B.selectByCondition - ==>  Preparing: select * from tb_brand where status = ? and company_name like ? and brand_name like ? 
[DEBUG] 17:02:01.454 [main] c.w.m.B.selectByCondition - ==> Parameters: 1(Integer), %华为%(String), %华为%(String) 
[DEBUG] 17:02:01.466 [main] c.w.m.B.selectByCondition - <==      Total: 1 
[Brand(id=2, brandName=华为, companyName=华为技术有限公司, ordered=100, description=华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界, status=1)]
小结

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_19

1.4.4 动态SQL ★

上述功能实现存在很大的问题。用户在输入条件时,肯定存在不是所有的条件都填写的情况,这个时候我们的SQL语句就不能那样写的

例如用户只输入 当前状态 时,SQL语句就是

select * from tb_brand where status = #{status}

而用户如果只输入企业名称时,SQL语句就是

select * from tb_brand where company_name like #{companName}

而用户如果输入了 当前状态企业名称 时,SQL语句又不一样

select * from tb_brand where status = #{status} and company_name like #{companName}

sql语句条件是动态变化的,只写一种所有参数的呢?不行,where status = null 会导致查不出来任何值

针对上述的需要,Mybatis对动态SQL有很强大的支撑:

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

我们先学习 if 标签和 where 标签:

  • if 标签:条件判断
  • test 属性:逻辑表达式
    注意:逻辑表达式里是companyName而非company_name 也就是判断传入的参数或者说占位符
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    where
        <if test="status != null">
            and 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>
</select>

如上的这种SQL语句就会根据传递的参数值进行动态的拼接。如果此时status和companyName有值那么就会值拼接这两个条件。

执行结果如下:(注释掉最后一个参数)

// 参数封装成对象
Map map = new HashMap();//值类型是变的 所以不能有范型
map.put("status",status);//key和映射sql里的占位符保持一致     说明: #{占位符}
map.put("companyName",companyName);
//map.put("brandName",brandName);
DEBUG] 17:54:37.342 [main] c.w.m.B.selectByCondition - ==>  Preparing: select * from tb_brand where status = ? and company_name like ? 
[DEBUG] 17:54:37.363 [main] c.w.m.B.selectByCondition - ==> Parameters: 1(Integer), %华为%(String) 
[DEBUG] 17:54:37.375 [main] c.w.m.B.selectByCondition - <==      Total: 1 
[Brand(id=2, brandName=华为, companyName=华为技术有限公司, ordered=100, description=华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界, status=1)]
[DEBUG] 17:54:37.382 [main] o.a.i.t.j.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@64ec96c6]

看sql语句,就拼接了2两个

但是它也存在问题,如果此时给的参数值是

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语句。这个就可以使用 where 标签解决

  • where 标签 (推荐)
  • 作用:
  • 替换where关键字
  • 会动态的去掉第一个条件前的 and
  • 如果所有的参数没有值则不加where关键字
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    <where>
        <if test="status != null">
            and 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>

注意:需要给每个条件前都加上 and 关键字。

  • 自己解决:恒等式
<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    where 1 = 1

    <if test="status != null">
        and 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>

</select>

1.5 单个条件(动态SQL)

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_20

如上图所示,在查询时只能选择 品牌名称当前状态企业名称 这三个条件中的一个,但是用户到底选择哪儿一个,我们并不能确定。这种就属于单个条件的动态SQL语句。

这种需求需要使用到 choose(when,otherwise)标签 实现, 而 choose 标签类似于Java 中的switch语句。

通过一个案例来使用这些标签

1.5.1 编写接口方法

BrandMapper 接口中定义单条件查询的方法。

/**
  * 单条件动态查询
  * @param brand
  * @return
  */
List<Brand> selectByConditionSingle(Brand brand);

1.5.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>
        </choose>
    </where>
</select>

1.5.3 编写测试方法

test/java 下的 cn.whu.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();
}

执行测试方法结果如下:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_sql_21

万一啥条件都没有,也会出bug.
解决方式有2种:
1:<otherwise>
2、直接用之前的<where>

  • 使用<otherwise>
<select id="selectByConditionSingle" resultMap="brandResultMap">
    select *
    from tb_brand
    where
    <choose><!--相当于switch 选择其中一个-->
        <when test="status != null"> /*相当于case*/
            status = #{status} /*单个条件,肯定没有and*/
        </when>

        <when test="companyName != null and companyName!=''">
            company_name like #{companyName}
        </when>

        <when test="brandName!=null and brandName!=''">
            brand_name like #{brandName}
        </when>
        <otherwise> /*保底的 where 后面不能一个条件都没有啊*/
            1 = 1
        </otherwise>
    </choose>
</select>
  • 使用<where>
<select id="selectByConditionSingle" resultMap="brandResultMap">
     select *
     from tb_brand
     <where>
         <choose><!--相当于switch 选择其中一个-->
             <when test="status != null">/*相当于case*/
                 status = #{status} /*单个条件,肯定没有and*/
             </when>

             <when test="companyName != null and companyName!=''">
                 company_name like #{companyName}
             </when>

             <when test="brandName!=null and brandName!=''">
                 brand_name like #{brandName}
             </when>
         </choose>
     </where>
 </select>

没有指定条件,就应该查询所有


-----------------------Mybatis配置文件增删改---------------------------

1.6 添加数据

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_22

如上图是我们平时在添加数据时展示的页面,而我们在该页面输入想要的数据后添加 提交 按钮,就会将这些数据添加到数据库中。接下来我们就来实现添加数据的操作。

  • 编写接口方法

    参数:除了id之外的所有的数据。id对应的是表中主键值,而主键我们是 自动增长 生成的。
  • 编写SQL语句
  • 编写测试方法并执行

明确了该功能实现的步骤后,接下来我们进行具体的操作。

1.6.1 编写接口方法

BrandMapper 接口中定义添加方法。

/**
   * 添加
   */
void add(Brand brand);

1.6.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>

1.6.3 编写测试方法

test/java 下的 cn.whu.mapper 包下的 MybatisTest类中 定义测试方法

注意mybatis会关闭自动提交: Setting autocommit to false on JDBC Connection
也就是需要你手动提交事务 (否则IDEA里显示添加成功,数据库里却查不到)

方法1: 手动提交事务: sqlSession.commit();
方法2:把自动提交事务打开:SqlSession sqlSession = sqlSessionFactory.openSession(true);

@Test
public void testAdd() throws Exception {
    // 接收参数
    String brandName = "菠萝手机";
    String companyName = "菠萝有限公司";
    int ordered = 100;
    String description = "美国有苹果,中国有菠萝";
    int status = 1;

    // 参数封装成对象
    Brand brand = new Brand();
    brand.setBrandName(brandName);
    brand.setCompanyName(companyName);
    brand.setOrdered(ordered);
    brand.setDescription(description);
    brand.setStatus(status); //默认启用

    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);//这里把自动提交事务打开也行

    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4. 执行方法
    mapper.add(brand);

    // mybatis需要手动提交事务
    sqlSession.commit();

    //5. 释放资源
    sqlSession.close();
}

执行结果如下:

[DEBUG] 19:57:26.363 [main] o.a.i.t.j.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3e2055d6] 
[DEBUG] 19:57:26.365 [main] c.w.m.B.add - ==>  Preparing: insert into tb_brand(brand_name, company_name, ordered, description, status) value(?,?,?,?,?) 
[DEBUG] 19:57:26.384 [main] c.w.m.B.add - ==> Parameters: 菠萝手机(String), 菠萝有限公司(String), 100(Integer), 美国有苹果,中国有菠萝(String), 1(Integer) 
[DEBUG] 19:57:26.385 [main] c.w.m.B.add - <==    Updates: 1 
[DEBUG] 19:57:26.385 [main] o.a.i.t.j.JdbcTransaction - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3e2055d6] 
[DEBUG] 19:57:26.386 [main] o.a.i.t.j.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3e2055d6] 
[DEBUG] 19:57:26.386 [main] o.a.i.t.j.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3e2055d6]

1.6.4 添加-主键返回

在数据添加成功后,有时候需要获取插入数据库那行数据的主键(主键是自增长)。

比如:添加订单和订单项,如下图就是京东上的订单

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_23

订单数据存储在订单表中,订单项存储在订单项表中。

  • 添加订单数据
  • 添加订单项数据,订单项中需要设置所属订单的id

明白了什么时候 主键返回 。接下来我们简单模拟一下,在添加完数据后打印id属性值,能打印出来说明已经获取到了。

我们将上面添加品牌数据的案例中映射配置文件里 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 :指定将获取到的主键值封装到哪儿个属性里

不配置,直接添加完直接用brand.getId(),得到的是null,没用
(这里也能看出不合理,自己插入的行数据,竟然有行内信息是自己不知道的)

再测试执行,testAdd()代码无需改动,add()方法后添加一行:

System.out.println(brand.getId());

即可

  • 小结:

1.7 修改

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_24

如图所示是修改页面,用户在该页面书写需要修改的数据,点击 提交 按钮,就会将数据库中对应的数据进行修改。注意一点,如果哪儿个输入框没有输入内容,我们是将表中数据对应字段值替换为空白还是保留字段之前的值?答案肯定是保留之前的数据。

接下来我们就具体来实现

1.7.1 编写接口方法

BrandMapper 接口中定义修改方法。

/**
   * 修改 : 返回值int 就是影响的行数
   */
int update(Brand brand);

上述方法参数 Brand 就是封装了需要修改的数据,而id肯定是有数据的,这也是和添加方法的区别。

--------修改全部字段--------

1.7.2 编写SQL语句

<update id="update">
     update tb_brand
     set brand_name = #{brandName},
         company_name = #{companyName},
         ordered = #{ordered},
         description = #{description},
         status = #{status}
     where id = #{id};
 </update>

1.7.3 编写测试方法

BrandMapper.xml 映射配置文件中编写修改数据的 statement

public void testUpdate() throws Exception {
        // 接收参数
        int id = 9;//要修改哪条数据
        String brandName = "菠萝手机2";
        String companyName = "菠萝无限公司";
        int ordered = 100;
        String description = "美国有苹果,中国有菠萝";
        int status = 1;

        // 参数封装成对象
        Brand brand = new Brand();
        brand.setId(id);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setStatus(status); //默认启用

        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //SqlSession sqlSession = sqlSessionFactory.openSession(true);//这里把自动提交事务打开也行

        //3. 获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 执行方法
        int count = mapper.update(brand);
        System.out.println(count);//count影响的行数
        // 返回值 影响的行数 可以获取到 输出为: 1

        // mybatis需要手动提交事务
        sqlSession.commit();

        //5. 释放资源
        sqlSession.close();
    }

执行结果如下:确实修改了所有的字段

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_25

--------动态修改部分字段--------

1.7.2 编写SQL语句

提交了的值修改,未提交的值不修改(保持原来的旧值) 多好的需求啊

<set>标签可以解决两个问题:1 是万一最后一个条件不成立引发的逗号,问题。2 是万一所有字段都为空,set多余的问题

BrandMapper.xml 映射配置文件中编写修改数据的 statement

<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>

set 标签可以用于动态包含需要更新的列,忽略其它不更新的列。

1.7.3 编写测试方法

test/java 下的 cn.whu.mapper 包下的 MybatisTest类中 定义测试方法

@Test
public void testUpdate() throws Exception {
    // 接收参数
    int id = 9;//要修改哪条数据
    String brandName = "菠萝手机2";
    String companyName = "菠萝无限公司";
    int ordered = 100;
    String description = "美国有苹果,中国有菠萝";
    int status = 0;

    // 参数封装成对象
    Brand brand = new Brand();
    /* 只设置两个值了 */
    brand.setId(id);
    brand.setStatus(status);

    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);//这里把自动提交事务打开也行

    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4. 执行方法
    int count = mapper.update(brand);
    System.out.println(count);//count影响的行数
    // 返回值 影响的行数 可以获取到

    // mybatis需要手动提交事务
    sqlSession.commit();

    //5. 释放资源
    sqlSession.close();
}

执行测试方法结果如下:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_26


从结果中SQL语句可以看出,只修改了 status 字段值,因为我们给的数据中只给Brand实体对象的 status 属性设置值了。这就是 set 标签的作用。

1.8 删除一行数据

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_27

如上图所示,每行数据后面都有一个 删除 按钮,当用户点击了该按钮,就会将该行数据删除掉。那我们就需要思考,这种删除是根据什么进行删除呢?是通过主键id删除,因为id是表中数据的唯一标识。

接下来就来实现该功能。

1.8.1 编写接口方法

BrandMapper 接口中定义根据id删除方法。

/**
  * 根据id删除
  */
void deleteById(int id);

1.8.2 编写SQL语句

BrandMapper.xml 映射配置文件中编写删除一行数据的 statement

<delete id="deleteById">
    delete from tb_brand where id = #{id};
</delete>

1.8.3 编写测试方法

test/java 下的 cn.whu.mapper 包下的 MybatisTest类中 定义测试方法

@Test
public void testDeleteById() throws Exception {
    // 接收参数
    int id = 12;//要删除哪条数据
    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);//这里把自动提交事务打开也行
    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    mapper.deleteById(id);
    // mybatis需要手动提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_28

运行过程只要没报错,直接到数据库查询数据是否还存在。发现确实删除了

  • 小结:

1.9 批量删除

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_29

如上图所示,用户可以选择多条数据,然后点击上面的 删除 按钮,就会删除数据库中对应的多行数据。

1.9.1 编写接口方法

BrandMapper 接口中定义删除多行数据的方法。

/**
  * 批量删除
  */
void deleteByIds(int[] ids);

参数是一个数组,数组中存储的是多条数据的id

1.9.2 编写SQL语句 (foreach 标签)

BrandMapper.xml 映射配置文件中编写删除多条数据的 statement

编写SQL时需要遍历数组来拼接SQL语句。Mybatis 提供了 foreach 标签供我们使用

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>

separator=“,”: 各个id之间’,'隔开
open=“(” close=“)”: 首尾拼接一个( ) 这样外层的括号,就不用写了

或者

void deleteByIds(@Param("ids") Integer[] ids);
<delete id="deleteByIds">
       delete from tb_brand
       where id in (           
           <foreach collection="ids" item="id" separator=",">
               #{id}
           </foreach>
           )
   </delete>

假如数组中的id数据是{1,2,3},那么拼接后的sql语句就是:

delete from tb_brand where id in (1,2,3);

1.9.3 编写测试方法

test/java 下的 cn.whu.mapper 包下的 MybatisTest类中 定义测试方法

@Test
public void testDeleteByIds() throws Exception {
    // 接收参数
    int[] ids = {11, 14, 15};//要删除哪条数据
    //1. 获取sqlSessionFactory
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    //2. 获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);//这里把自动提交事务打开也行
    //3. 获取mapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    mapper.deleteByIds(ids);
    // mybatis需要手动提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_java_30

1.10 Mybatis参数传递

Mybatis 接口方法中可以接收各种各样的参数,如下:

  • 多个参数
  • 单个参数:单个参数又可以是如下类型
  • POJO 类型
  • Map 集合类型
  • Collection 集合类型
  • List 集合类型
  • Array 类型
  • 其他类型

1.10.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);

简言之,不指定key,每个参数就都有两个默认的key
[“arg0” 或者 “param1”] [“arg1” 或者 “param2”] … [“argX-1” 或者 “paramX”]

代码验证:

  • 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>
  • 运行代码结果如下(Test方法和上面一模一样)

在映射配合文件的SQL语句中使用用 arg 开头的和 param 书写,代码的可读性会变的特别差,此时可以使用 @Param 注解。

在接口方法参数上使用 @Param 注解,Mybatis 会将 arg 开头的键名替换为对应注解的属性值。

代码验证:

  • UserMapper 接口中定义如下方法,在 username 参数前加上 @Param 注解
User select(@Param("username") String username, String password);

Mybatis 在封装 Map 集合时,键名就会变成如下:

map.put(“username”,参数值1);

map.put(“arg1”,参数值2);

map.put(“param1”,参数值1);

map.put(“param2”,参数值2);

  • UserMapper.xml 映射配置文件中定义SQL
<select id="select" resultType="user">
	select *
    from tb_user
    where 
    	username=#{username}
    	and password=#{param2}
</select>
  • 运行程序结果没有报错。而如果将 #{} 中的 username 还是写成 arg0
<select id="select" resultType="user">
	select *
    from tb_user
    where 
    	username=#{arg0}
    	and password=#{param2}
</select>
  • 运行程序则可以看到错误

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_31

结论:以后接口参数是多个时,在每个参数上都使用 @Param 注解。这样代码的可读性更高。★

拓展: 事先知道mybatis进行参数获取封装的类是ParamNameResolver 对应的方法是:getNamedParams
于是: 双击shift->搜索ParamNameResolver -> 鼠标放到类名处-> alt+7 -> 点击getNamedParams方法 打个断点,慢慢看,深入理解框架·。和python看AI框架一样 ★

看源码就很容易理解了: 注解指定了参数名称,优先使用注解的参数名称,没有注解才使用默认的: “param”+(i+1) 或者”arg“+i

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_sql_32

1.10.2 单个参数 (各种集合类型的默认key参数,但是不建议使用默认key)

  • POJO 类型
    直接使用。要求 属性名参数占位符名称 一致
  • Map 集合类型
    直接使用。要求 map集合的键名参数占位符名称 一致
  • Collection 集合类型
    Mybatis 会将集合封装到 map 集合中,如下:

map.put(“arg0”,collection集合);

map.put(“collection”,collection集合);

可以使用 @Param 注解替换map集合中默认的 arg 键名。建议【Collection、List、Array 、前面的多个参数】 都这么使用,增强可读性

  • List 集合类型
    Mybatis 会将集合封装到 map 集合中,如下:

map.put(“arg0”,list集合);

map.put(“collection”,list集合);

map.put(“list”,list集合);

  • 可以使用 @Param 注解替换map集合中默认的 arg 键名。
  • Array 类型
    Mybatis 会将集合封装到 map 集合中,如下:

map.put(“arg0”,数组);

map.put(“array”,数组);

  • 可以使用 @Param 注解替换map集合中默认的 arg 键名。
  • 其他类型
    比如int类型,参数占位符名称 叫什么都可以。尽量做到见名知意
    单个简单类型,随便写,只有一个嘛,肯定不会有歧义的。

wrapToMapIfCollection 方法里打断点,很好理解上面的缘由

  • 小结:
  • 思考:map.put(“user”,user),占位符怎么写?
    很简单:key肯定还是那个key,也就是"user",至于属性名,本来就可以直接用,也就是 #{user.username}即可

2,注解实现CRUD (简单查询神器)

使用注解开发会比配置文件开发更加方便。如下就是使用注解进行开发

@Select(value = "select * from tb_user where id = #{id}")
public User select(int id);

注意:

  • 注解是用来替换映射配置文件方式配置的,所以使用了注解,就不需要再映射配置文件中书写对应的 statement

Mybatis 针对 CURD 操作都提供了对应的注解,已经做到见名知意。如下:

  • 查询 :@Select
  • 添加 :@Insert
  • 修改 :@Update
  • 删除 :@Delete

2.1 注解查询@Select

接下来我们做一个案例来使用 Mybatis 的注解开发

代码实现:

  • 将之前案例中 UserMapper.xml 中的 根据id查询数据 的 statement 注释掉
  • UserMapper 接口的 selectById 方法上添加注解
@Select("select * from tb_user where id = #{id}")
    User selectById(int id);
  • 运行测试程序也能正常查询到数据
@Test
    public void testSelectById() throws Exception {
        //接收数据
        int id = 1;

        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 获取mapper接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 执行方法
        User user = mapper.selectById(id);
        System.out.println(user);

        //5. 释放资源
        sqlSession.close();
    }

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_SQL_33

2.4 注解添加@Insert

  • *在 UserMapper 接口里编写如下方法和注解
@Insert("insert into tb_user values(null,#{username},#{password},#{gender},#{addr}) ")
 void add(User user);
  • test/java 下的 cn.whu.mapper 包下的 UserMapperTest类中 定义测试方法
@Test
    public void testInsert() throws Exception {
        //接收数据
        String username = "紫英";
        String password = "456789";
        String gender = "男";
        String addr = "昆仑山琼华派";
        // 封装对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setGender(gender);
        user.setAddr(addr);

        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 执行方法
        mapper.add(user);
        // 别忘了mybatis手动提交事务
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();
    }
  • 查询数据库 确实插入了

2.3 注解修改@Update

  • *在 UserMapper 接口里编写如下方法和注解
// 注解开发想要动态sql(有值才修改 就麻烦了 自己拼sql 还不防注入)
    @Update("update tb_user set username=#{username},password=#{password},gender=#{gender},addr=#{addr} " +
            "where id = #{id}")
    void update(User user);
  • test/java 下的 cn.whu.mapper 包下的 UserMapperTest类中 定义测试方法
@Test
    public void testUpdate() throws Exception {
        //接收数据
        int id = 7;
        String username = "重光";
        String password = "110";
        String gender = "男";
        String addr = "昆仑山琼华派清风涧";
        // 封装对象
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setGender(gender);
        user.setAddr(addr);

        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 执行方法
        mapper.update(user);
        // 别忘了mybatis手动提交事务
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();
    }

2.2 注解删除@Delete

  • *在 UserMapper 接口里编写如下方法和注解
@Delete("delete from tb_user where id = #{id}")
    void deleteById(int id);
  • test/java 下的 cn.whu.mapper 包下的 UserMapperTest类中 定义测试方法
@Test
    public void testDeleteById() throws Exception {
        //接收数据
        int id = 8;

        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 执行方法
        mapper.deleteById(id);
        // 别忘了mybatis手动提交事务
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();
    }

2.3 结果集映射

  • *在 BrandMapper 接口里编写如下方法和注解
@Results(id="brandResultMap",value = {//指定id属性 以后就可以复用了
            @Result(column = "id", property = "id",id = true),/*名称相同其实不需要 完全为了演示主键*/
            @Result(column = "brand_name",property = "brandName"),
            @Result(column = "company_name",property = "companyName")
    })
    void method();//缓冲方法 定义注解

    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")//不加此行,有些不同名字段 查询结果为null
    List<Brand> selects();
  • test/java 下的 cn.whu.mapper 包下的 MybatisTest类中 定义测试方法
@Test
    public void testSelects() throws Exception {
        //1. 获取sqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 执行方法
        List<Brand> brands = mapper.selects();
        System.out.println(brands);
        //5. 释放资源
        sqlSession.close();
    }

全都查到了,不错

[DEBUG] 19:41:32.920 [main] c.w.m.B.selects - ==>  Preparing: select * from tb_brand 
[DEBUG] 19:41:32.936 [main] c.w.m.B.selects - ==> Parameters:  
[DEBUG] 19:41:32.947 [main] c.w.m.B.selects - <==      Total: 5 
[Brand(id=1, brandName=三只松鼠, companyName=三只松鼠股份有限公司, ordered=5, description=好吃不上火, status=0), Brand(id=2, brandName=华为, companyName=华为技术有限公司, ordered=100, description=华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界, status=1), Brand(id=3, brandName=小米, companyName=小米科技有限公司, ordered=50, description=are you ok, status=1), Brand(id=9, brandName=菠萝, companyName=菠萝有线公司, ordered=100, description=美国有苹果,中国有菠萝, status=0), Brand(id=10, brandName=菠萝手机, companyName=菠萝有限公司, ordered=100, description=美国有苹果,中国有菠萝, status=1)]

2.4 小结

注意:在官方文档中 入门 中有这样的一段话:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_34

所以,注解完成简单功能,配置文件完成复杂功能。

而我们之前写的动态 SQL 就是复杂的功能,如果用注解使用的话,就需要使用到 Mybatis 提供的SQL构建器来完成,而对应的代码如下:

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_开发语言_35


上述代码将java代码和SQL语句融到了一块,使得代码的可读性大幅度降低。

  • 小结
    XML肯定更容易维护,修改sql也不需要改.java代码而导致要重新打包。
    注解最大的优势就是简单。但是复杂动态sql咋办捏?注解太烦了甚至有些不行。(自己拼接sql简单,但是可能有注入问题)
    而且,现在有了插件mybatisX, XML配置法也复杂不到哪里去了
    个人觉得:可以采用 XML 模式与注解模式混用,也就是简单 SQL 语句采用注解模式,复杂 SQL 语句采用 XML 模式。为最佳

02-MyBatis-CRUD-配置文件、参数封装、mybatisX插件、动态sql, 简单的用注解开发_mybatis_36

简单的就用注解,复杂的,简单结果集映射(表列名和pojo字段名不一致)也还行,再复杂就麻烦了,跟着教程用xml吧


标签:02,mapper,插件,配置文件,brand,sqlSession,status,SQL,id
From: https://blog.51cto.com/u_15798167/6443817

相关文章

  • 02-前端-javaScript
    文章目录JavaScript1,JavaScript简介2,JavaScript引入方式2.1内部脚本2.2外部脚本3,JavaScript基础语法3.1书写语法3.2输出语句3.3变量3.3.1全局变量var3.3.2局部变量let3.3.3常量const3.4数据类型3.5运算符3.5.1\==和===区别▲3.5.2类型转换3.6流程控制语句3.6.1if......
  • javaWeb核心02-Request&Response -(乱码处理、字符流、字节流、虚拟目录、请求转发、重
    文章目录Request&Response1,Request和Response的概述2,Request对象2.1Request继承体系2.2Request获取请求数据2.2.1获取请求行数据2.2.2获取请求头数据2.2.3获取请求体数据2.2.4获取请求参数的通用方式基于上述理论,request对象为我们提供了如下方法:★代码演示2.3IDEA快速创......
  • visualstudio2022 ef6生成代码报错
    StartNotepadinadministratormode,andopenthefile(substitutingCommunityforProfessionalorEnterprisedependingonyourversion):C:\ProgramFiles\MicrosoftVisualStudio\2022\Community\Common7\IDE\Extensions\Microsoft\EntityFrameworkTo......
  • SONiC 202305 Release内容
    SONiC社区采用Github平台进行项目管理,Github平台不仅仅提供代码的托管服务,还能提供IsuueTracking,Releasemanagement等RequirementEngineering的功能。在GithubSONiC页面上选择Projects/SONiC202305Release以后,可以看到表格的形式显示的该Release计划的77个Issue的内容。到......
  • P8376 [APIO2022] 排列
    一种比较容易写的构造方案考虑直接二进制拆分,发现在原排列的基础上,在开头填上更大的数,方案数+1,在末尾上填上更大的数,方案数*2,直接按照填数从小到大顺序填入,长度为logk+popcount(k),期望得分91分1#include<bits/stdc++.h>23usingnamespacestd;45vector<int......
  • 2023年4月阅读笔记1
    为什么巴比伦塔会失败巴比伦塔的制造是一个神话故事,但是其中的道理却对今天人们的协作有着重要的启示。软件系统的开发完全通过计算机执行,为什么还是很少有远程协作的企业,这是因为远程协作很容易导致交流的缺失。大型的软件项目开发需要团队中的每个人能及时了解到整个团队在做些......
  • 2023年4月阅读笔记2
    未雨绸缪我们在实现功能时往往有很多思路,但是哪种思路能行得通并且最适合情况就需要我们进行试验性开发。试验性开发确实会造成精力的消耗,或许大量的测试方案最终还会被舍弃,但是我们必须这样做。实际上如果不进行方案的实验,正式的开发反而可能遭遇返工和混乱的拆补,会严重分散重新......
  • 2023年4月阅读笔记3
    整体部分面向对象编程的“封装”思想和结构化编程的“精化”思想对于整个软件开发过程的各个粒度同样适用。整体的顺利运行离不开各个组成部分的优化。编码时各个信息隐藏的模块需要完成各自的任务,再通过接口互相配合。测试时需要从最小的单元测试开始,每一粒度都测试完全时,整个系......
  • Vue——登录小案例、scoped、ref属性、props其他、混入mixin、插件、Element-ui
    解析Vue项目#1为什么浏览器中访问某个地址,会显示某个页面组件 根组件:APP.vue必须是 <template><divid="app"><router-view></router-view></div> </template>1配置路由 router--->index.js---&......
  • 各类配置文件(DNS, Firefox,Edge)
    DNS配置腾讯DNS:119.29.29.292402:4e00:: 2402:4e00:1::阿里云:223.5.5.5223.6.6.62400:3200::12400:3200:baba::1黑龙江联通:202.97.224.68202.97.224.69CiscoDNS208.67.222.222208.67.220.2202620:119:35::352620:119:53::53浏览器配置Firefoxabout:confi......