MyBatis 配置文件和注解完成增删改查使用的超详细介绍

配置文件完成增删改查

环境搭建

数据库表 tb_brand

创建数据库tb_btand

-- 创建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);

SELECT * FROM tb_brand;

定义实体类 Brand

public class Brand {
    
    
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private String ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;

    public Brand() {
    
    }

    public Brand(Integer id, String brandName, String companyName, String 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(int 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 String getOrdered() {
    
    
        return ordered;
    }

    public void setOrdered(String 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(int status) {
    
    
        this.status = status;
    }

    @Override
    public String toString() {
    
    
        return "Brand{" +
                "id='" + id + '\'' +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered='" + ordered + '\'' +
                ", description='" + description + '\'' +
                ", status='" + status + '\'' +
                '}';
    }
}

测试用例MyBatisTest

public class MyBatisTest {
    
    
}

安装 MyBatisX 插件:

MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。

主要功能:

  • XML 和 接口方法 相互跳转
  • 根据接口方法生成 statement

查询数据

完成下面查询功能:

查询所有

查看详情

条件查询

查询所有

需求:

封装成一个Brand对象, 并添加到一个List集合中

步骤分析:

1.定义Mapper接口, 编写方法:

  • 有无参数:无
  • 返回结果:List<Brand>

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

实现过程如下:

  1. 创建一个BrandMapper接口
public interface BrandMapper {
    
    
    List<Brand> selectAll();
}
  1. 映射文件中编写sql语句
<?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.chenyq.mapper.BrandMapper">
    <select id="selectAll" resultType="Brand">
        SELECT * FROM tb_brand;
    </select>
</mapper>
  1. 测试: 执行测试方法
@Test
public void testSelectAll() throws Exception {
    
    
    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

    // 3. 获取BrandMapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    List<Brand> brands = brandMapper.selectAll();
    // 打印结果
    System.out.println(brands);

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

解决名称不匹配请问那天

问题注意: 数据库的字段名称和实体类的名称不一样, 则不能自动封装数据, 解决方式有下面两种:

方式一: 起别名, 编写sql语句的时候, 给名称不一样的字段名, 取一个与实体类属性名一样的别名

  • 缺点: 每次查询都需要取别名
<mapper namespace="com.chenyq.mapper.BrandMapper">
		<!-- 给名称不一样的字段取别名 -->
    <select id="selectAll" resultType="Brand">
        select id, brand_name as brandName, company_name as companyName,
            ordered, description, status
        from tb_brand;
    </select>
</mapper>

方式二: 通过resultMap映射

  • resultMap标签中有id和result两个标签
  • id用于主键字段的映射, result用于完成一般字段的映射
<!-- id: 唯一标识, type: 映射的类型, 支持别名 -->
<resultMap id="brandResultMap" type="brand">
    <!-- column: 表的列名, property: 实体类的属性名 -->
    <result column="user_name" property="userName" />
    <result column="company_name" property="companyName" />
</resultMap>

<!-- 使用resultMap属性替换resultType属性, 用于绑定resultMap标签 -->
<select id="selectAll" resultMap="brandResultMap">
    SELECT * FROM tb_brand;
</select>

查询详情

需求:

根据id查看某商品的详情信息

步骤分析:

1.编写接口方法: Mapper接口

  • 参数:id
  • 返回结果:Brand

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

实现过程如下:

编写接口方法

public interface BrandMapper {
    
    
    Brand selectById(int id);
}

Mapper映射文件中, 编写SQL语句

<mapper namespace="com.chenyq.mapper.BrandMapper">
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName" />
        <result column="company_name" property="companyName" />
    </resultMap>
  
    <select id="selectById" resultMap="brandResultMap">
        select * from tb_brand where id = #{id};
    </select>
</mapper>

测试: 编写测试方法

@Test
public void testSelectById() throws Exception {
    
    
    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

    // 3. 获取BrandMapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    Brand brand = brandMapper.selectById(3);
    // 打印结果
    System.out.println(brand);

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

条件查询

多条件查询(传递多个参数)

在这里插入图片描述

需求:

将满足条件的数据封装为Brand对象, 再转入List集合返回

分析步骤:

1.编写接口方法: Mapper接口

  • 参数:所有查询条件, 传递多个参数
  • 返回结果:List<Brand>

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

传递多个参数有三种方式:

  1. 散装参数
  2. 对象参数
  3. map集合参数

方式一: 散装参数

有多个参数时, 需要使用@Param('SQL语句参数占位符名称')注解标注该参数对应sql语句中的哪一个占位符

编写接口方法

public interface BrandMapper {
    
    
		// 散装参数的方式编写接口方法
    List<Brand> selectByCondition(@Param("status") int status,
                                  @Param("companyName") String companyName,
                                  @Param("brandName") String brandName);
}

编写SQL语句

<select id="selectByCondition" resultMap="brandResultMap">
    select * from tb_brand
    where status = #{status}
        and company_name like #{companyName}
        and brand_name like #{brandName}
</select>

Test方法测试

@Test
public void selectByCondition() throws Exception {
    
    
    // 接收参数
    int status = 1;
    String brandName = "小米";
    String companyName = "小米";

    // 处理参数模糊查询
    brandName = "%" + brandName + "%";
    companyName = "%" + companyName + "%";

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

    // 3. 获取BrandMapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
  
  	// 传入散装参数
    List<Brand> brands = brandMapper.selectByCondition(status, brandName, companyName);
    System.out.println(brands);

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

方式二: 对象参数

作为参数的对象的属性名称要与SQL语句的参数占位符一致

编写接口方法

public interface BrandMapper {
    
    
    // 对象参数的方式编写接口方法
    List<Brand> selectByCondition(Brand brand);
}

SQL语句和散装参数的一样

Test测试方法中, 需要将参数封装成一个对象传入

@Test
public void selectByCondition() throws Exception {
    
    
    // 接收参数
    int status = 1;
    String brandName = "小米";
    String companyName = "小米";

    // 处理参数模糊查询
    brandName = "%" + brandName + "%";
    companyName = "%" + companyName + "%";

    // 将参数封装成对象
    Brand brand = new Brand();
    brand.setStatus(status);
    brand.setBrandName(brandName);
    brand.setCompanyName(companyName);

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

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

    // 传入对象参数
    List<Brand> brands = brandMapper.selectByCondition(brand);
    System.out.println(brands);

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

方式三: Map集合参数

需要保证SQL中的参数占位符和map集合的键的名称对应上,即可设置成功

定义Map集合参数方法

public interface BrandMapper {
    
    
    // 定义map集合参数方法
    List<Brand> selectByCondition(Map map);
}

SQL语句同样不需要修改

Test方法中, 需要将参数封装到Map集合中传入

@Test
public void selectByCondition() throws Exception {
    
    
    // 接收参数
    int status = 1;
    String brandName = "小米";
    String companyName = "小米";

    // 处理参数模糊查询
    brandName = "%" + brandName + "%";
    companyName = "%" + companyName + "%";

    // 将参数封装成Map集合
    Map map = new HashMap();
    map.put("status", status);
    map.put("brandName", brandName);
    map.put("companyName", companyName);

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

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

    // 传入Map集合参数
    List<Brand> brands = brandMapper.selectByCondition(map);
    System.out.println(brands);

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

三种参数定义的方式是可以共存的:

public interface BrandMapper {
    
    ;
    // 定义散装参数的方法
    List<Brand> selectByCondition(@Param("status") int status,
                                  @Param("companyName") String companyName,
                                  @Param("brandName") String brandName);
    // 定义对象参数的方法
    List<Brand> selectByCondition(Brand brand);
    // 定义map集合参数方法
    List<Brand> selectByCondition(Map map);
}

多条件查询-动态条件

其实我们上面写的多条件查询的代码是有bug的:

上面代码中我们是根据三个条件共同查询的, 思考一下, 用户再使用的时候是否会将三个或者更多的条件全部填写?

其实很多时候都是不会全部填写的, 上面代码中, 一旦有一个条件没有填写那么就会查询不到数据

为解决上面的问题, 我们需要使用动态条件查询:

SQL语句会随着用户的输入或外部条件的变化而变化,我们也称为动态SQL

MyBatis 对动态SQL有很强大的支撑, 提供了下面一些标签(本节演示if和where标签, 其他标签下文中会进行演示)

if

choose (when, otherwise)

trim (where, set)

foreach

MyBatisif和where标签的使用:

动态条件查询只是动态的改变SQL语句, 定义接口方法和测试用例与前面完全没有区别;

if标签中的test属性中写逻辑表达式, 如下:

<!-- 动态条件查询 -->
<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>
</select>

但是这样也会存在问题, companyName和brandName参数不传没有问题, 但是status不传, SQL语句的语法就会错误, where后面直接跟了一个and;

解决方式一: 让所有的if标签中的SQL语句前面都加上一个and, 在where添加后面跟一个恒成立式, 例如1=1

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

解决方式二: 使用MyBatis提供的where标签将if标签进行一层包裹, where标签会在and多余的时候, 自动的帮我们去除and

<select id="selectByCondition" resultMap="brandResultMap">
    select * from tb_brand
	  <!--where标签包裹 -->
    <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>

单条件查询-动态条件

动态单条件查询: 有多个条件根据用户动态选择的条件进行查询

在这里插入图片描述

使用choose (when, otherwise):选择,choose类似于Java中的switch, when类似于switch中的case, otherwise类似于switch中的default

分析步骤:

1.编写接口方法: Mapper接口

  • 参数:传入Brand对象, 根据对象有值的条件进行查询
  • 返回结果:List<Brand>

2.编写 SQL语句: choose (when, otherwise)

3.执行方法,测试

实现过程如下:

编写接口方法

public interface BrandMapper {
    
    
    List<Brand> selectByConditionSingle(Brand brand);
}

使用choose (when, otherwise)编写SQL语句

<!-- 动态单条件查询 -->
<select id="selectByConditionSingle" resultMap="brandResultMap">
    select * from tb_brand
    where
    <choose> <!-- 类似于switch -->
        <when test="status != null"> <!-- 类似于when -->
            status = #{status}
        </when>
        <when test="companyName != null and companyName != ''">
            company_name like #{companyName}
        </when>
        <when test="brandName != null and brandName != ''">
            brand_name like #{brandName}
        </when>
        <otherwise> <!-- 类似于default -->
            1 = 1
        </otherwise>
    </choose>
</select>

执行测试方法

@Test
public void selectByConditionSingle() throws Exception {
    
    
    // 接收参数
    String companyName = "华为";

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

    // 将参数封装成对象
    Brand brand = new Brand();
    brand.setCompanyName(companyName);

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

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

    List<Brand> brands = brandMapper.selectByConditionSingle(brand);
    System.out.println(brands);

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

添加数据

基础添加

步骤分析:

1.编写接口方法: Mapper接口

  • 参数:除了id之外的所有数据
  • 返回结果:void, 无返回结果

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

过程如下:

编写接口方法

public interface BrandMapper {
    
    
    void add(Brand brand);
}

编写SQL语句

<!-- 基础添加 -->
<insert id="add">
    insert
    into tb_brand (brand_name,
        company_name,
        ordered,
        description,
        status)
    value (#{brandName},
        #{companyName},
        #{ordered},
        #{description},
        #{status}}});
</insert>

执行测试方法: 注意MyBatis是自动开启了事务, 我们修改完成后需要手动提交事务

@Test
public void testAdd() throws Exception {
    
    
    // 接收参数
    String brandName = "香飘飘";
    String companyName = "香飘飘有限公司";
    String ordered = "10";
    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. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession();

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

    // 4. 提交事务
    sqlSession.commit();

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

如果不想开启事务, 希望自动提交事务, 可以在获取SqlSession对象时传递一个参数true

SqlSession sqlSession = sqlSessionFactory.openSession(true);

主键返回

主键返回:

在数据添加成功后,需要获取插入数据库数据的主键

比如:添加订单和订单项, 一个订单对应多个订单项

在添加订单后, 添加的订单项需要设置外键指向所属订单的主键id

其实这个操作非常简单, 只需要设置insert标签中useGeneratedKeys和keyProperty的属性值

  • 将useGeneratedKeys设置为true
  • 将keyProperty设置为主键的字段名称
  • <insert useGeneratedKeys="true" keyProperty="id">

例如我们将上面基础添加设置主键返回, 在添加完后会将id返回

<!-- 主键返回 -->
<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>

此时添加完成后, 可以通过对象获取返回的主键id

// 添加完成后可以获取到id
int id = brand.getId();
System.out.println(id);

修改数据

修改全部字段

分析步骤:

1.编写接口方法: Mapper接口

  • 参数:所有数据
  • 返回结果:int, 影响的行数

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

实现过程:

编写接口方法

public interface BrandMapper {
    
    
    int update(Brand brand);
}

编写SQL方法

<!-- 修改全部字段 -->
<update id="update">
    update tb_brand
    set
        brand_name = #{brandName},
        company_name = #{companyName},
        ordered = #{ordered},
        description = #{description},
        status = #{status}
    where id = #{id};
</update>

编写测试方法

@Test
public void testUpdate() throws Exception {
    
    
    // 接收参数
    String brandName = "飘飘香";
    String companyName = "飘飘香有限公司";
    String ordered = "10";
    String description = "飘飘香绕地球一圈";
    int status = 0;
    int id = 4;

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

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession(true);

    // 3. 获取BrandMapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    int count = brandMapper.update(brand );

    // 处理结果
    if (count > 0) {
    
    
        System.out.println("修改成功");
    } else {
    
    
        System.out.println("修改失败");
    }

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

修改动态字段

根据用户的需求动态的修改某一个或几个字段

在sql语句中加上if标签判断, 并且使用set标签对条件包裹

set标签包裹, 可以防止一个判断都不生效情况下的语法报错, 还可以解决语句多出来逗号问题

<!-- 修改动态字段 -->
<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 and ordered != ''">
            ordered = #{ordered},
        </if>
        <if test="description != null and description != ''">
            description = #{description},
        </if>
        <if test="status != null">
            status = #{status}
        </if>
    </set>
    where id = #{id};
</update>

删除数据

删除一个

根据id删除一条数据

步骤分析:

1.编写接口方法: Mapper接口

  • 参数:id
  • 返回结果:void

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

实现过程:

编写接口方法

public interface BrandMapper {
    
    
    void deleteById(int id);
}

编写sql语句

<!-- 删除一个 -->
<delete id="deleteById">
    delete
    from tb_brand
    where id = #{id};
</delete>

编写测试方法测试

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

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession(true);

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

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

批量删除

批量删除, 接收一个id数组, 删除数据, 由于删除的数据的id数组, 是不固定的, 所以需要用到foreach标签

步骤分析:

1.编写接口方法: Mapper接口

  • 参数:id数组
  • 返回结果:void

2.编写 SQL语句: SQL映射文件

3.执行方法,测试

实现过程:

编写接口方法

public interface BrandMapper {
    
    
	  /**
        MyBatis会将数组参数封装为一个Map集合
         * map集合key的默认名称是array
         * 使用@Param注解可以改变map集合默认的名称
     */
    void deleteByIds(@Param("ids") int[] ids);
}

编写sql语句

<!-- 批量删除 -->
<delete id="deleteByIds">
    delete
    from tb_brand
    where id in (
        <foreach collection="ids" item="id" separator=",">
            <!-- collection: 遍历Map集合哪一个key, item: 遍历后的名称 separator: 以什么分隔-->
            #{id}
        </foreach>
    );
</delete>

编写测试方法测试

@Test
public void testDeleteByIds() throws Exception {
    
    
    // 接收参数
    int[] ids = {
    
    1, 2, 3};

    // 1. 加载MyBatis的核心配置文件, 获取SqlSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2. 获取SqlSession对象, 用来执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession(true);

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

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

注解完成增删改查

使用注解开发会比配置文件开发更加方便

注解开发: 在定义接口方法的上面添加注解, 就不需要去XML文件中单独编写sql语句

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

提示:

注解完成简单功能的sql语句, 对于稍微复杂的sql语句, Java注解就力不从心, 还会让本就复杂的语句更加混乱不堪

配置文件完成复杂功能

示例代码, 注解完成根据id查询数据:

public interface BrandMapper {
    
    
    @Select("select * from tb_brand where id = #{id}")
    Brand selectById(int id);
}

猜你喜欢

转载自blog.csdn.net/m0_71485750/article/details/127845667