首页 > 技术文章 > mybaits 修改语句中,如果传值就修改某个字段,如果不传值就不修改某个字段

zxxshare 2017-02-17 09:48 原文

接到一个需求,修改一张表,字段如果传值了即修改,若没有传值则不修改。

感觉这就不是什么复杂的需求,<if></if>判断一下就行了,但是写出来之后发现要判断的有点多啊,看起来很冗余啊,然后就想mybaits有木有自行判断处理这种情况的方法呢。

后来发现,是有的~~

1、第一种写法

<trim prefix="set" suffixOverrides=",">
  <if test="a != null and a != ''"> column1=#{a},</if>
  <if test="b != null and b != ''"> column2=#{b},</if>
  <if test="c != null and c != ''"> column3=#{c},</if>
  <if test="d != null and d!= ''"> column4=#{d},</if>
</trim>

 

2、第二种写法

<set>
  <if test="a != null and a != ''"> column1=#{a},</if>
  <if test="b != null and b != ''"> column2=#{b},</if>
  <if test="c != null and c != ''"> column3=#{c},</if>
  <if test="d != null and d!= ''"> column4=#{d},</if>
</set>

 

推荐阅读