mybatis实现动态修改数据set标签的使用

动态修改和动态查询变化不是很大,只是换了一个set标签。简单演示,总共分为3步骤

一、写接口

 //动态修改数据
    int modify(Brand brand);

在这里插入图片描述

二、写SQL

<!--    动态修改数据-->
    <update id="modify">
        update tb_brand
        <set>
            <if test="status != null ">
                status = #{status},
            </if>
            <if test="companyName != null and companyName != '' ">
                company_name = #{companyName},
            </if>

            <if test="brandName != null and brandName != '' ">
                brand_name = #{brandName},
            </if>
            <if test="description != null and description != '' ">
                description = #{description},
            </if>
        </set>
        where id = #{id}
    </update>

在这里插入图片描述

三、写测试用例

这里就和新增一条数据差不多,无需多言。

 @Test
    public void testModify() throws IOException {
        //1.获取sqlSessionFactort
        //①加载mybatis的核心配置文件,获取sqlSessionFatory对象,从官网复制,
        String resource = "mybatis-config.xml"; //直接复制配置文件路径,注意是mybatis的
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.
        int statue = 1;
        String companyName = "修改手机01";
        String brandName = "修改手机";
        int ordered = 3332;
        String description = "modify";
        int id = 6;


        Brand brand1 = new Brand();
//        brand1.setStatus(statue);
        brand1.setCompanyName(companyName);
        brand1.setBrandName(brandName);
        brand1.setDescription(description);
        brand1.setOrdered(ordered);
        brand1.setId(id);

        int modify = mapper.modify(brand1);
        System.out.println("修改成功条数: " + modify);

        //5.
        sqlSession.close();
    }

在这里插入图片描述

小结一下啊

其实就是一个set标签的使用,没有什么复杂的地方。需要注意的地方:
①每一个if语句后面都是一个逗号,就和多条件查询的and一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值