一、概述
mybatis的xml中trim标签有四个属性
prefix 前缀增加的内容
suffix 后缀增加的内容
prefixOverrides 前缀需要覆盖的内容,一般是第一个判断条件前面的多余的结构,如:第一个判断条件前面多了 ‘and’
suffixOverrides 后缀需要覆盖的内容,一般是最后一个数据的后面符号,如:set值的时候,最后一个值的后面多一个逗号‘,’
二、举例说明
根据用户姓名和年龄查询用户,有什么值就根据什么条件(目的是说明几个属性用法,可能例子不适用于实际场景中)
<select id='queryUser'>
select * from User
<trim prefix='where' prefixOverrides='and'>
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="age !=null and age !=''">
and age = #{age}
</if>
</trim>
<select>
上面例子是很常规的一个写法,第一个条件前面没有任何符号,第二个条件要加上and,否则sql语句会报错。很理想的状态是第一个和第二个都有值,但是既然判断,说明也可能会没有值,当第一个name没有值的时候,这个时候sql语句就会是 select * from User where and age='',很明显这个sql语句语法存在问题。在这里标签属性prefixOverrides就起作用了,它会让前缀where覆盖掉第一个and。覆盖之后的是:select * from User where age='';前缀加上where就不说,因为属性 prefix='where',这个where 也可以写在<trim>标签的外面,这样此处就无需用到属性prefix了。
现在有更方便的标签了,就是<where>,用这个标签效果一样的,会忽略掉第一个符合条件前面的符号。
select * from User
<where>
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="age !=null and age !=''">
and age = #{age}
</if>
</where>
如果第一个name值是null,则age前面的and会被忽略掉。
再说说另两个属性,suffix和suffixOverrides
<update id="updateUser">
update User
<trim prefix="set" suffixOverrides="," suffix="where id='1'">
<if test="name != null and name != ''">
name=#{name},
</if>
<if test="age != null and age !=''">
age=#{age},
</if>
</trim>
</update>
本例中最后一个条件中的逗号“,”会被后缀覆盖掉,本例中的后缀是where id =‘1’;
OK,纯属为了说明四个属性怎么使用的,具体里面的值会根据具体需求而定。