Mybatis学习笔记(6)-MyBatis updateByExample和updateByExampleSelective的区别

我们在使用MyBatis时,通常使用逆向工程工具生成一套接口和xml映射文件用于简单的单表操作,而其中有两个比较常用的接口方法,一个是 updateByExample ,一个是  updateByExampleSelective  ,它们的作用是对数据库进行更新操作。

通过查看逆向工程的xml映射文件可以发现,这两个方法的区别是:

updateByExample需要将表的条件全部给出,比如一个一个表有三个字段,就必须给三个字段给他,不给会设为null,如以下代码:

 <update id="updateByExample" parameterType="map" >
    update tb_item
    set id = #{record.id,jdbcType=BIGINT},
      title = #{record.title,jdbcType=VARCHAR},
      sell_point = #{record.sellPoint,jdbcType=VARCHAR},
      price = #{record.price,jdbcType=BIGINT},
      num = #{record.num,jdbcType=INTEGER},
      barcode = #{record.barcode,jdbcType=VARCHAR},
      image = #{record.image,jdbcType=VARCHAR},
      cid = #{record.cid,jdbcType=BIGINT},
      status = #{record.status,jdbcType=TINYINT},
      created = #{record.created,jdbcType=TIMESTAMP},
      updated = #{record.updated,jdbcType=TIMESTAMP}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>

而updateByExampleSelective不同,当某一实体类的属性为null时,mybatis会使用动态sql过滤掉,不更新该字段:

<update id="updateByExampleSelective" parameterType="map" >
    update tb_item
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.title != null" >
        title = #{record.title,jdbcType=VARCHAR},
      </if>
      <if test="record.sellPoint != null" >
        sell_point = #{record.sellPoint,jdbcType=VARCHAR},
      </if>
      <if test="record.price != null" >
        price = #{record.price,jdbcType=BIGINT},
      </if>
      <if test="record.num != null" >
        num = #{record.num,jdbcType=INTEGER},
      </if>
      <if test="record.barcode != null" >
        barcode = #{record.barcode,jdbcType=VARCHAR},
      </if>
      <if test="record.image != null" >
        image = #{record.image,jdbcType=VARCHAR},
      </if>
      <if test="record.cid != null" >
        cid = #{record.cid,jdbcType=BIGINT},
      </if>
      <if test="record.status != null" >
        status = #{record.status,jdbcType=TINYINT},
      </if>
      <if test="record.created != null" >
        created = #{record.created,jdbcType=TIMESTAMP},
      </if>
      <if test="record.updated != null" >
        updated = #{record.updated,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>

结论:最好使用updateByExampleSelective,因为它能根据所需进行更新操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BoringRong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值