trim元素的主要功能是可以在自己包含的内容钱加上某些前缀,也可以在其后加上某写后缀,与之对应的属性是prefix和suffix;
可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides。以下举例:
1、代码为:
select * from user
"WHERE" prefixOverrides="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>
假如说name和gender的值都不为null的话,打印的SQL为:
select * from user where name = 'xx' and gender = 'xx'
where后不存在and,这是因为prefixOverrides="AND |OR"
代表去掉第一个and或者是or。
2、代码为:
update user
"set" suffixOverrides="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0"> name=#{name} , if>
<if test="gender != null and gender.length()>0"> AND gender=#{gender} , if>
假如说name和gender的值都不为null的话,打印的SQL为:
update user set name='xx' , gender='xx' where id='x'
可以参考第一个例子理解。
3、代码为:
<insert id="save" parameterType="NoticeEntity">
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>
insert>
大家可以自行理解一下。