我们在使用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,因为它能根据所需进行更新操作。