MyBatis中配置文件实现增删改查

配置文件完成增删改查:

完成品牌数据的增删改查操作

要完成的功能列表清单:

​ 1、查询:

​ 查询所有数据

​ 查看详情

​ 条件查询

​ 2、添加

​ 3、修改:

​ 修改全部字段

​ 修改动态字段

​ 4、删除:

​ 删除一个

​ 批量删除

准备环境:

​ 数据库表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);


SELECT * FROM tb_brand;

​ 实体类 Brand

package com.itheima.pojo;

/**
 * 品牌
 *
 * alt + 鼠标左键:整列编辑
 *
 * 在实体类中,基本数据类型建议使用其对应的包装类型
 */

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

1、查询:

查询 - 查询所有数据

​ 1、编写接口方法:Mapper接口

​ 参数:无

​ 返回结果:List

List<Brand> selectAll();

​ 2、编写SQL语句:SQL映射文件

<select id = "selectAll" resultType = "Brand">
	select * from tb_brand;
</select>

​ 3、执行方法,测试

参考代码:

mybatis核心文件

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

    <!-- 扫描包后,这个包下的类可以直接使用类名作路径,且不区分大小写 -->
    <typeAliases>
        <package name = "com.itheima.pojo"/>
    </typeAliases>

    <!--
     environments:配置数据库连接环境信息,可以配置多个environment,通过default属性与environment中的id来匹配
    -->
    <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="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 加载sql的映射文件 -->
<!--        <mapper resource="com\itheima\mapper\UserMapper.xml"/>-->

        <!-- Mapper代理方式 -->
        <package name="com.itheima.mapper"/>

    </mappers>
</configuration>
<?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">

<!--
    SQL映射文件
 -->
<mapper namespace="com.itheima.mapper.BrandMapper">
    <!--
        数据库表的字段名称 和 实体类的属性名称一样,则不能自动封装数据
            1、起别名:对不一样的列名起别名,让别名和实体类的属性名一样
                缺点:每次查询都要定义一次别名
                在此基础上使用sql片段
                    缺点:不灵活

            2、resultMap:
                定义<resultMap>标签
                在<select>标签中,使用resultMap属性替换resultType属性

    -->

    <!--
        id:唯一标识
        type:映射的类型,支持别名
    -->

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

    <!-- =============================================== -->

    <!--
        sql片段
     -->
<!--    <sql id="brand_column">-->
<!--        id, brand_name as brandName, company_name as companyName, ordered, description, status-->
<!--    </sql>-->

<!--    <select id="selectAll" resultType="brand">-->
<!--        select-->
<!--            &lt;!&ndash; 将对应的sql片段放在这个位置 &ndash;&gt;-->
<!--            <include refid="brand_column"/>-->
<!--        from tb_brand;-->
<!--    </select>-->

    <!-- =============================================== -->

    <!--    <select id="selectAll" resultType="Brand">-->
<!--        select * from tb_brand;-->
<!--    </select>-->

</mapper>
//对应接口
package com.itheima.mapper;

import com.itheima.pojo.Brand;

import java.util.List;

public interface BrandMapper {
    /**
     * 查询所有
     */
    public List<Brand> selectAll();
}
package com.itheima.test;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest {
    @Test
    public void testSelectAll() throws IOException {
        //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.selectAll();   //将来就写这一行
        System.out.println(brands);

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

问题:当数据库中的表的列名与实体类中的属性名不一样是,读取数据有问题

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

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

查询 - 查看详情

1、编写接口:Mapper接口

​ 参数:id

​ 结果:Brand

Brand selectById(int id);

2、执行SQL语句:SQL映射文件

<select id = "selectById" parameterType = "int" resultType = "Brand">
	select * from tb_brand where id = #{id};
</select>

3、执行方法,测试

参考代码:

接口中添加的方法:

/**
     * 根据id,查看详情
     */
    public Brand selectById(int id);

SQL映射添加内容

<!--
        参数占位符:
            1、#{}:会将其替换为?占位符,防止SQL注入
            2、${}:拼接SQL会存在SQL注入问题
            3、使用时机:
                参数传递时:#{}
                表名或者列名不固定的情况下:${},会存在SQL注入问题

         参数类型:parameterType,可以省略
         特殊字符的处理:
            1、转义字符:特殊字符较少
            2、CDATA区:特殊字符较多
     -->

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

    <select id="selectById" parameterType="int" resultMap="brandResultMap">
        select * from tb_brand where id
        <![CDATA[
            <
        ]]>
        #{id};
    </select>

测试方法:

 	@Test
    public void testSelectById() throws IOException {
        //定义一个id模拟接收到的 id值
        int id = 1;

        //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、执行方法
        Brand brand = brandMapper.selectById(id);
        System.out.println(brand);

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

查询 - 多条件查询

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

​ 参数:所有查询条件

​ 结果:List

List<Brand> selectByCondition(@Param("status"))int status, @Param("companyName") String companyName, @Param("brandName") String brandName);

List<Brand> selectByCondition(Brand brand);

List<Brand> selectByCondition(Map map);

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

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

3、执行方法,测试

/**
     * 条件查询
     *   1、散装的参数:如果方法中有多个参数,需要使用@Param("SQL映射中的参数占位符名称,即#{}中的")
     *   2、对象参数:对象的属性名称要和参数占位符名称一致
     *   3、map集合参数
     *
     *
     * @param status
     * @param companyName
     * @param brandName
     * @return
     */
//    List<Brand> selectByCondition(@Param("status")int status, @Param("companyName") String companyName, @Param("brandName") String brandName);

//    List<Brand> selectByCondition(Brand brand);

    List<Brand> selectByCondition(Map map);
	<!-- 条件查询的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
    public void testSelectByCondition() 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);

        Map map = new HashMap();
        map.put("status", status);
        map.put("companyName", companyName);
        map.put("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、执行方法
//        List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
//        List<Brand> brands = brandMapper.selectByCondition(brand);
        List<Brand> brands = brandMapper.selectByCondition(map);
        System.out.println(brands);

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

问题:用户是否会将三个条件都输入,如果空一个and就将不成立,就会出现BUG

查询 - 多条件 - 动态条件查询

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

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

Mybatis 对动态SQL有很强大的支撑:

​ if

​ choose(when, otherwise)

​ trim(where, set)

​ foreach

<!--
        动态条件查询
            if:条件判断
                test:逻辑表达式
            问题:当前面的条件不满足式,可能会出现SQL语法错误
                1、使用恒等式
                2、使用<where>标签 替换 where关键字
    -->
    <select id = "selectByCondition" resultMap = "brandResultMap">
        select *
        from tb_brand
<!--        where 1 = 1-->
        <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):选择,类似于Java中的switch语句

<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 != ''">	
        	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 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();
    }
2、添加:

添加

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

​ 参数:除了id之外的所有数据

​ 结果:void

void add(Brand brand);

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

<insert id = "add">
	insert into tb_brand(brand_name, company_name, ordered, description, status)
    values(#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>

3、执行测试方法

MyBatis事务:

​ openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit(); 手动提交事务

​ openSession(true):可以设置为自动提交事务(关闭事务)

测试代码:

	//添加
    @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);    //表示自动提交事务
        //参数为false 就是不开启事务

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

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

        //手动提交事务,否则事务会回滚,则数据无法添加到表中
        sqlSession.commit();

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

添加 - 主键返回

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

​ 比如:添加订单和订单项

1、添加订单

2、添加订单项,订单项中需要设置所属订单的id

<insert id = "addOrder" userGeneratedKeys = "true" keyProperty = "id">	<!-- 添加了这两个属性后可以获取主键 -->
	insert into tb_order(payment, payment_type, status)
    values (#{payment}, #{paymentType}, #{status});
</insert>
<insert id = "addOrderItem">
	insert into tb_order_item (goods_name, good_pirce, count, order_id)
    values (#{goodsName}, #{goodsPrice}, #{count}, #{order});
</insert>
3、修改

修改全部字段

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

​ 参数:所有数据

​ 结果:void

void update(Brand brand);

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

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

3、执行方法,测试

	//修改 - 修改全部字段
    @Test
    public void testupdate() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "波导手机";
        String brandName = "波导";
        String description = "波导手机,手机中的战斗机";
        int ordered = 200;
        int id = 4;

        //封装成对象
        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();  //默认开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);    //表示自动提交事务
        //参数为false 就是不开启事务

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

        //4、执行方法
        int count = brandMapper.update(brand);
        System.out.println(count);

        //手动提交事务,否则事务会回滚,则数据无法添加到表中
        sqlSession.commit();

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

修改动态字段

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

​ 参数:部分数据,封装到对象中

​ 结果:void

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

<uppdate 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};
</uppdate>

3、执行方法,测试

	@Test
    public void testUpdate() throws IOException {
        //接收参数
        int status = 0;
        String companyName = "波导手机";
        String brandName = "波导";
        String description = "波导手机,手机中的战斗机";
        int ordered = 200;
        int id = 4;

        //封装成对象
        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();  //默认开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);    //表示自动提交事务
        //参数为false 就是不开启事务

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

        //4、执行方法
        int count = brandMapper.update(brand);
        System.out.println(count);

        //手动提交事务,否则事务会回滚,则数据无法添加到表中
        sqlSession.commit();

        //5、释放资源
        sqlSession.close();
    }
4、删除

删除一个

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

​ 参数:id

​ 结果:void

void deleteById(int id);

2、编写SQL

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

3、执行方法,测试

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

        //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);    //表示自动提交事务
        //参数为false 就是不开启事务

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

        //4、执行方法
        brandMapper.deleteById(id);

        //手动提交事务,否则事务会回滚,则数据无法添加到表中
        sqlSession.commit();

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

批量删除

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

参数:id数组

结果:void

void deleteByIds(@Param("ids")int[] ids);

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

<delete id = "deleteByIds">
	delete from tb_brand
    <!-- 问号的个数不定,使用动态SQL改进 -->
    where id in (?,?,?);
</delete>
<delete id = "deleteByIds">
	delete from tb_brand
    where id in
    <!-- 这个数组或者集合 、 每一项的字段 、 中间使用什么间隔 、 开始或者结束时拼接什么(所以这里省略的大括号) -->
    <foreach collection = "ids" item = "id" separator = "," open = "("close=")">
    	#{id};
    </foreach>
</delete>

3、执行方法,测试

	<!-- 批量删除的SQL映射 -->
    <delete id="deleteByIds">
        delete from tb_brand where id
        in
            <!--
                mybatis会将数组参数,封装为一个Map集合。
                    默认:array = 数组
                    使用@Param注解改变map集合的默认key的名称
             -->
<!--            <foreach collection="array" ></foreach>-->
            <foreach collection="ids" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        
    </delete>
		@Test		
		public void testDeleteByIds() throws IOException {
        //接收参数
        int[] ids = {2, 3, 7};

        //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);    //表示自动提交事务
        //参数为false 就是不开启事务

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

        //4、执行方法
        brandMapper.deleteByIds(ids);

        //手动提交事务,否则事务会回滚,则数据无法添加到表中
        sqlSession.commit();

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

MyBatis参数传递

MyBatis 接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式

单个参数:

​ 1、POJO类型:直接使用,属性名 和 参数占位符名称一致

​ 2、Map集合:直接使用,键名 和 参数占位符名称一致

​ 3、Collection:封装为Map集合

​ map.put("arg0", collection集合);

​ map.put("collection", collection集合);

​ 4、List:封装为Map集合

​ map.put("arg0", list集合);

​ map.put("collection", list集合);

​ map.put("list", list集合);

​ 5、Array:封装为Map集合

​ map.put("arg0", 数组);

​ map.put("array", 数组);

​ 6、其他类型:直接使用

多个参数:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put("arg0", 参数值1)
map.put("param1", 参数值1)
map.put("param2", 参数值2)
map.put("arg1", 参数值2)
------------------------------@Param("username")
map.put("username", 参数值1)
map.put("param1", 参数值1)
map.put("param2", 参数值2)
map.put("arg1", 参数值2)

MyBatis提供了ParamNameResolver类来进行参数封装,双击shift搜索查看

结论:不要使用默认键名,都使用@Param注解来修改Map集合中默认的键名,并且使用修改后的名称来获取值,这样可读性更高

注解完成增删改查

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

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

查询:@Select

添加:@Insert

修改:@Update

删除:@Delete

提示:

​ 注解完成简单功能

​ 配置文件完成复杂功能

​ 使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java注解不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好使用XML来映射语句。

​ 选择何种方式来配置映射文件,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和XML的语句映射方式间自由移植和切换。

posted @ 2023-01-21 10:20  如此而已~~~  阅读(71)  评论(0编辑  收藏  举报