trim元素的主要功能是可以在自己包含的內容錢(qián)加上某些前綴,也可以在其后加上某寫(xiě)后綴,與之對應的屬性是prefix和suffix;可以把包含內容的首部某些內容覆蓋,即忽略,也可以把尾部的某些內容覆蓋,對應的屬性是prefixOverrides和suffixOverrides。以下舉例:1、代碼為:select * from user <trim prefix="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> </trim>假如說(shuō)name和gender的值都不為null的話(huà),打印的SQL為:select * from user where name = 'xx' and gender = 'xx'where后不存在and,這是因為prefixOverrides="AND |OR"代表去掉第一個(gè)and或者是or。
2、代碼為:update user <trim prefix="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> </trim>假如說(shuō)name和gender的值都不為null的話(huà),打印的SQL為:update user set name='xx' , gender='xx' where id='x'可以參考第一個(gè)例子理解。
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>大家可以自行理解一下。
聯(lián)系客服