当更新表时,只更新值不为空的字段。需要用<if>
判断传入的值是否不为空,然后更新值不为空对应的字段。
<update id="updatePerson">
<!-- Set标签的使用 -->
update PERSON
set
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
where id=#{id}
</update>
上述示例,set 是SQL中的关键字,当哪个if条件判断成功后就插入更新哪个字段,但是上述示例存在一个弊端。如果上述示例中所有的判断都成功时,SQL不存在问题,但当gender判断不成功时,SQL的拼接语句就变成了:
update PERSON set last_name=#{
lastName}, email=#{
email}, where id=#{
id}
从拼接后的语句可以看出,where关键字前面多了一个“,”,结果导致SQL语句失败。
修正方式一:
通过使用<set>
标签来修正上述方式,只需要把上述所有的判断语句放在<set>
标签即可。因为<set>
标签既有set关键字的作用,还可以自动去掉<set>
标签包裹的拼接后的字符串的最后一个“,”。示例如下
<update id="updatePerson">
<!-- Set标签的使用 -->
update PERSON
<set>
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</set>
where id=#{id}
</update>
当gender判断不成功时, 标签可以把包裹的字符串拼接的最后一个“,”去掉,就变成了:
set last_name=#{
lastName}, email=#{
email}
修正方式二:
通过使用<trim>
(已在前一节演示)标签进行修正
<update id="updatePerson">
update PERSON
<trim prefix="set" suffixOverrides=",">
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</trim>
where id=#{id}
</update>
当gender判断不成功后,<trim>
标签包裹的字符串拼接后为:
last_name=#{
lastName}, email=#{
email},
<trim prefix="set" suffixOverrides=",">
指定在拼接的字符串的前面加上set,并且把拼接字符串的最后的“,”去掉,因此最后就变成了:set last_name=#{lastName}, email=#{email}
最后的SQL语句为:
update PERSON set last_name=#{
lastName}, email=#{
email} where id=#{
id}