updateByPrimaryKey和updateByPrimaryKeySelective的区别

MyBatis Generator概述

  • MyBatis Generator是一个专门为MyBatis框架使用者定制的代码生成器,它可以快速的根据表生成对应的映射文件、接口文件、POJO。而且,在自动生成的映射文件中支持基本的增删改查操作,开发人员可在此基础上依据实际需求添加多表联查、存储过程等复杂SQL操作。
  • MyBatis Generator使用简单,通常只需要很少量的简单配置就可以完成大量的表到POJO生成工作,让开发人员解放出来更专注于业务逻辑的开发。
  • 在使用MyBatis Generator时自动生成了updateByPrimaryKey和updateByPrimaryKeySelective用于执行依据主键进行更新操作。

updateByPrimaryKey

  • 我们先来看第一种调用updateByPrimaryKey ( )方法依据主键进行更新。在使用该方式时需尤其注意以下情况。当Java对象的某属性有值时,在数据库更新记录时会将该属性值更新至原纪录对应的字段。但是,当Java对象的某属性未设置值时,在数据库更新记录时会将对应字段的值设置为null。
  • 映射文件中的updateByPrimaryKey核心代码如下:
<update id="updateByPrimaryKeySelective" parameterType="Worker" >
    update worker
    <set >
      <if test="wName != null" >
        w_name = #{wName,jdbcType=VARCHAR},
      </if>
      <if test="fId != null" >
        f_id = #{fId,jdbcType=INTEGER},
      </if>
    </set>
    where w_id = #{wId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cn.pojo.Worker" >
    update worker
    set w_name = #{wName,jdbcType=VARCHAR},
      f_id = #{fId,jdbcType=INTEGER}
    where w_id = #{wId,jdbcType=INTEGER}
  </update>

updateByPrimaryKeySelective

  • 为了避免updateByPrimaryKey ( )方法可能出现的情况,我们可使用updateByPrimaryKeySelective ( )方法执行选择性更新。当Java对象的某属性有值时,在数据库更新记录时会将该属性值更新至原纪录对应的字段。当Java对象的某属性未设置值时,在数据库更新记录时不会将对应字段的值设置为null。类似地,既然该方法是依据主键值进行更新,那么,Java对象的主键属性值不能为空。
  • 映射文件中的updateByPrimaryKeySelective核心代码如下:
<update id="updateByPrimaryKeySelective" parameterType="Worker" >
    update worker
    <set >
      <if test="wName != null" >
        w_name = #{wName,jdbcType=VARCHAR},
      </if>
      <if test="fId != null" >
        f_id = #{fId,jdbcType=INTEGER},
      </if>
    </set>
    where w_id = #{wId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cn.pojo.Worker" >
    update worker
    set w_name = #{wName,jdbcType=VARCHAR},
      f_id = #{fId,jdbcType=INTEGER}
    where w_id = #{wId,jdbcType=INTEGER}
  </update>
  • 从以上代码我们可以明显看出:updateByPrimaryKeySelective较updateByPrimaryKey而言多了非空判断。这正是两者区别的根源所在。

小结

  • 一般情况下,在实际项目开发中执行依据主键进行更新时推荐使用updateByPrimaryKeySelective ( )方法。
  • 同理、updateByExample与updateByExampleSelective 也存在类似的差异。所以,一般情况下,在实际项目开发中执行依据条件选择性更新时推荐使用updateByExampleSelective ( )方法。