在前文《mybatis动态SQL-<if>标签详解》中,讲述了<if>标签在where查询、insert插入和update更新三种操作中的使用方法,在where查询语句中涉及到了根据参数值是否为空的where条件查询,在update中涉及到了根据参数值是否为空的set赋值操作,本文接下来就重点说说这两个操作中经常会用到的<where>标签和<set>标签。
先分别看一下<where>标签和<set>标签在xml文件中的使用方法:
<where>标签使用方法:
<select id="selectListByCondition" resultMap="sysUserMap" parameterType="Sysuser">
select <include refid="sysUserSql"/>
from sys_user
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="userName != null and userName !=''">
and user_name like concat('%', #{userName}, '%')
</if>
<if test="userCode != null and userCode != ''">
and user_code = #{userCode}
</if>
<if test="userInfo != null and userInfo != ''">
and user_info like concat('%', #{userInfo}, '%')
</if>
<if test="status != null and status != ''">
and status = #{status}
</if>
</where>
</select>
这里我们之前曾用过where 1 = 1 ,目的是为了防止<if>中条件为真时,where后面直接跟上and。
那么当使用<where>标签时,就不再需要where 1 = 1了。
<where>标签的作用:如果该标签包含的元素中有返回值(<if>标签内OGNL表达式为真)时,就插入一个where,如果where后面紧接着的字符串是以AND或者OR开头的,就将他们去除。
<set>标签使用方法:
<update id="updateSysUser">
<!--update sys_user set user_name = #{userName}, user_code = #{userCode}, user_info = #{userInfo}, status = #{status} where id = #{id}-->
update sys_user
<set>
<if test="userName != null and userName !=''">
user_name = #{userName},
</if>
<if test="userCode != null and userCode != ''">
user_code = #{userCode},
</if>
<if test="userInfo != null and userInfo != ''">
user_info = #{userInfo},
</if>
<if test="status != null and status != ''">
status = #{status},
</if>
id = #{id} where id = #{id}
</set>
</update>
<set>标签的作用:如果该标签包含的元素中有返回值(<if>标签内OGNL表达式为真)时,就插入一个set,如果set语句最后一个字符串是以逗号结尾的,就将这个逗号去除。
分析完了<where>标签和<set>标签后,我们看看<trim>标签的作用。
<where>标签和<set>标签的功能可以用<trim>标签来实现,并且在底层代码中,就是通过TrimSqlNode来实现的。
<where>标签对应的<trim>标签的写法如下:
<where>...</where>
<trim prefix="WHERE" prefixOverrides="AND | OR ">...</trim>
注意:prefixOverrides="AND | OR "中的AND和OR后面的空格不能省略,防止匹配到andes、orders等单词。
<set>标签对应的<trim>标签的写法如下:
<set>...</set>
<trim prefix="SET" suffixOverrides=",">...</trim>
上面是<where>和<set>标签使用<trim>标签替换的写法,接下来看看<trim>标签中的几个属性:
prefix:当<trim>标签内包含内容时,会给内容增加prefix指定的前缀,如where或set;
suffix:当<trim>标签内包含内容时,会给内容增加suffix指定的后缀;
prefixOverrides:当<trim>标签内包含内容时,会把内容中匹配的前缀字符串去掉;
suffixOverrides:当<trim>标签内包含内容时,会把内容中匹配的后缀字符串去掉。