MyBatis学习笔记——MyBatis updateByExample方法和updateByExampleSelective方法的区别

使用 MyBatis,通常会使用 MyBatis Generator 插件逆向生成一套接口和.xml映射文件, 来简化数据库SQL操作。在进行数据库的更新时,通常会用到映射出来的mapper的两个更新方法:updateByExample(Record recode, RecordExample example)updateByExampleSelective(Record recode, RecordExample example)。这里记录下两者区别。

  1. updateByExample 方法对应的xml文件如下:
  <update id="updateByExample" parameterType="map">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Dec 01 11:10:13 CST 2019.
    -->
    update USER
    set ID = #{record.id,jdbcType=INTEGER},
      ACCOUNT_ID = #{record.accountId,jdbcType=VARCHAR},
      NAME = #{record.name,jdbcType=VARCHAR},
      TOKEN = #{record.token,jdbcType=VARCHAR},
      GMT_CREATE = #{record.gmtCreate,jdbcType=BIGINT},
      GMT_MODIFIED = #{record.gmtModified,jdbcType=BIGINT},
      AVATAR_URL = #{record.avatarUrl,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>

可以看到,updateByExample 会更新所有字段,没有给出的将会被赋为 null

  1. updateByExampleSelective 方法对应的xml文件如下:
  <update id="updateByExampleSelective" parameterType="map">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Dec 01 11:10:13 CST 2019.
    -->
    update USER
    <set>
      <if test="record.id != null">
        ID = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.accountId != null">
        ACCOUNT_ID = #{record.accountId,jdbcType=VARCHAR},
      </if>
      <if test="record.name != null">
        NAME = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.token != null">
        TOKEN = #{record.token,jdbcType=VARCHAR},
      </if>
      <if test="record.gmtCreate != null">
        GMT_CREATE = #{record.gmtCreate,jdbcType=BIGINT},
      </if>
      <if test="record.gmtModified != null">
        GMT_MODIFIED = #{record.gmtModified,jdbcType=BIGINT},
      </if>
      <if test="record.avatarUrl != null">
        AVATAR_URL = #{record.avatarUrl,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>

可以看到,updateByExampleSelective 方法采用的策略略有不同,如果某个字段为空,那么 Mybatis 将跳过该字段,只更新 record 中有的字段,算是“按需更新”。

总结: 最好还是使用 updateByExampleSelective 方法进行更新操作,特别是在有自增主键ID,又有字段ID的情况下(比如上边xml文件中的 record.idrecord.accountId),传递过来的 Record 是没有主键字段的,如果使用 updateByExample 根据字段ID进行更新是达不到预期效果的,它将会新建一条记录,但字段ID又和数据库中已有的那个字段ID相等,只是自增主键不同。使用 updateByExampleSelective 可以达到预期的“按字段ID更新”的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值