(十一)MyBatis的动态SQL:trim元素
生活随笔
收集整理的這篇文章主要介紹了
(十一)MyBatis的动态SQL:trim元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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>?
總結
以上是生活随笔為你收集整理的(十一)MyBatis的动态SQL:trim元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 迄今为止惠普最好的二合一电脑迄今为止惠普
- 下一篇: Hibernate: You have