使用 MyBatis,通常会使用 MyBatis Generator 插件逆向生成一套接口和.xml映射文件, 来简化数据库SQL操作。在进行数据库的更新时,通常会用到映射出来的mapper的两个更新方法:updateByExample(Record recode, RecordExample example)
和 updateByExampleSelective(Record recode, RecordExample example)
。这里记录下两者区别。
- 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
。
- 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.id
和 record.accountId
),传递过来的 Record 是没有主键字段的,如果使用 updateByExample 根据字段ID进行更新是达不到预期效果的,它将会新建一条记录,但字段ID又和数据库中已有的那个字段ID相等,只是自增主键不同。使用 updateByExampleSelective 可以达到预期的“按字段ID更新”的效果。