您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)MyBatis中怎么實現(xiàn)動態(tài)SQL!,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
一、if標(biāo)簽
if是最常用標(biāo)簽,經(jīng)常用在判斷語句上,可以實現(xiàn)某些簡單的條件選擇?;臼褂檬纠缦拢?/p>
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user where 1=1 <if test="name != null and name != ''"> and name = #{name} </if> <if test="age != null "> and age = #{age} </if> </select>
二、where標(biāo)簽
上面的例子中使用了“1=1”,是為了避免后續(xù)條件不滿足時候報錯,那有沒有辦法避免這種寫法呢?
當(dāng)然有,就是接下來要說的where,where標(biāo)簽會自動判斷如果包含的標(biāo)簽中有返回值的話,就在sql中插入一個where,如果where標(biāo)簽最后返回的內(nèi)容是以and 或者or開頭的,也會被自動移除掉,上面例子中換成where標(biāo)簽后寫法如下:
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user <where> <if test="name != null and name != ''"> and name = #{name} </if> <if test="age != null "> and age = #{age} </if> </where> </select>
三、trim標(biāo)簽
trim的作用是去除特殊的字符串,它的prefix屬性代表語句的前綴,prefixOverrides屬性代表需要去除的哪些特殊字符串,prefixOverrides屬性會忽略通過管道分隔的字符,后綴的處理和前綴一樣。
trim標(biāo)簽的主要屬性如下
prefix:前綴覆蓋并增加其內(nèi)容。
suffix:后綴覆蓋并增加其內(nèi)容。
prefixOverrides:前綴判斷的條件。
suffixOverrides:后綴判斷的條件。
舉兩個例子。
使用前綴屬性
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user <trim prefix="WHERE" prefixOverrides="AND |OR " > <if test="name != null and name != ''"> and name = #{name} </if> <if test="sex != null "> or sex = #{sex} </if> <if test="age != null "> and age = #{age} </if> </trim> </select>
使用后綴屬性
<update id="update" parameterType="Object"> UPDATE user <trim prefix=" SET " prefixOverrides=","> <if test="id != null ">,id=#{id}</if> <if test="name != null ">,name=#{name}</if> <if test="age != null ">,age=#{age}</if> </trim> WHERE ID=#{id} </update>
四、foreach標(biāo)簽
foreach的作用是遍歷集合,它能夠很好地支持?jǐn)?shù)組和List、Set接口的集合的遍歷,往往和sql中的in組合比較多。
foreach標(biāo)簽的主要屬性如下
item:表示循環(huán)中當(dāng)前的元素。
index:表示當(dāng)前元素在集合的位置下標(biāo)。
collection:配置list的屬性名等。
open和close:配置的是以什么符號將這些集合元素包裝起來。
separator:配置的是各個元素的間隔符。
舉個例子:
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user where id in <foreach item="id" index="index" collection="userList" open="(" separator="," close=")"> #{id} </foreach> </select>
關(guān)于MyBatis中怎么實現(xiàn)動態(tài)SQL!就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。