MyBatis——配置文件完成增删改查——修改

一、修改

  • 修改全部字段
  • 修改动态字段

(一)修改全部字段

  • 编写接口方法: Mapper接口 :void update(Brand brand);
  • 参数:所有数据
  • 结果: void
  • 编写SQL语句:SQL映射文件
  • 执行方法,测试

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

   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 = "华硕手机平板电脑";
        int ordered = 56;
        String description = "华硕飞行堡垒电脑是你的最佳选择";
        int id = 7;

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


        //1、加载核心配置文件,获取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、执行sql
        //List<User> users = sqlSession.selectList("test.selectAll");

        //3.1 通过SqISession的getMapper方法获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //3.2 调用对应方法完成sql的执行
        brandMapper.update(brand);

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

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

    }

缺点:
用户如果只想改其中一个字段,而不输入其他字段的值,那么为输入的属性就会修改成null,非常不灵活。

(二)修改动态字段

用户修改哪个字段是不固定的,那么SQL语句就不能写死,要用动态SQL。结合之前学到的动态SQL
使用if标签和set标签

    <update id="update">
        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="ordered != null ">
                ordered = #{ordered},
            </if>
            <if test="description != null and description!= ''">
                description = #{description}
            </if>
        </set>
        where id = #{id};
    </update>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值