trim标记是一个格式化的标记,可以完成select,update,insert语句的格式化操作。trim元素的主要功能有四个:
(1)可以在包含的内容前加上某些前缀,与之对应的属性是prefix;
(2)也可以在包含的内容后加上某写后缀,与之对应的属性是suffix;
(3)可以把包含内容的首部某些内容覆盖,即忽略,对应的属性是prefixOverrides
(4)也可以把包含内容的尾部的某些内容覆盖,对应的属性是suffixOverrides。
以下举例说明一下trim元素的应用场景:
例子1:
select * from user
<trim prefix="WHERE" prefixoverride="AND|OR"><if test="name != null and name.length()>0"> AND name=#{name}</if><if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
</trim>
假如说name和gender的值都不为null的话打印的SQL为:
select * from user where name = 'xx' and gender = 'xx'
where后不存在and,这是因为prefixOverrides="AND|OR"代表去掉第一个and或者是or。
例子2:
update user
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} "><if test="name != null and name.length()>0"> name=#{name} , </if><if test="gender != null and gender.length()>0"> gender=#{gender} , </if>
</trim>
假如说name和gender的值都不为null的话打印的SQL为:
update user set name='xx', gender='xx' where id='x'
在gender='xx'后面不存在逗号,而且自动加了一个set前缀和where后缀。
例子3:
INSERT INTO S_NOTICE
<trim prefix="(" suffix=")" suffixOverrides=",">ID,<if test="title != null">TITLE,</if><if test="content != null">CONTENT,</if><if test="noticeStatus != null">NOTICE_STATUS,</if><if test="createdBy != null">CREATED_BY,</if>CREATED_TS,<if test="lastUpdBy != null">LAST_UPD_BY,</if>LAST_UPD_TS,
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">SYS_GUID(),<if test="title != null">#{title,jdbcType=VARCHAR},</if><if test="content != null">#{content,jdbcType=VARCHAR},</if><if test="noticeStatus != null">#{noticeStatus,jdbcType=VARCHAR},</if><if test="createdBy != null">#{createdBy,jdbcType=VARCHAR},</if>systimestamp,<if test="lastUpdBy != null">#{lastUpdBy,jdbcType=VARCHAR},</if>systimestamp,
</trim>