MyBatis中動(dòng)態(tài)SQL的動(dòng)態(tài)使用
動(dòng)態(tài)SQL是指在MyBatis中根據不同的條件生成不同的SQL語(yǔ)句,它可以根據參數的動(dòng)態(tài)不同,動(dòng)態(tài)地改變SQL語(yǔ)句的動(dòng)態(tài)結構,從而實(shí)現更加靈活的動(dòng)態(tài)查詢(xún)和更新操作。
1、使用<if>標簽判斷條件是動(dòng)態(tài)否滿(mǎn)足:
<select id="findUsers" parameterType="map" resultType="User"> SELECT * FROM user <where> <if test="username != null and username != ''"&(′ω`*)gt; AND username = #{ username(′▽?zhuān)?)} <┐(′ー`)┌/if>?? <if test="age !=?? null&quo(′▽?zhuān)?t;> AND age = #{ age} </if> </where></select>在上述示例中,如果傳入(ru)的動(dòng)態(tài)參數中包含username且不為空(′?`)字符串,則會(huì )添加AND username?? = #{ username}的動(dòng)態(tài)條件;如果傳入的參數中包含age且不為null,則會(huì )添加AND age = #{ age}的動(dòng)態(tài)條件。
2、動(dòng)態(tài)使用<choose>、??動(dòng)態(tài)<when>和&??lt;otherwise>ヽ(′ー`)ノ;標簽進(jìn)行多條件判斷:
<select id="findUsers" parameterTyp( ???)e="map" resultType=&q??uot;User">??; SE(′?`*)LECT(?_?;) * FROM user <where??> <choose>(???); <when te??st="username != null and usernaヽ(′ー`)ノme != ''"> AND username = #{ userna???me} </when> <when test="age != null">(′Д` ) AND age = #{ age} </when> <otherwise> <!默認條件 > </othe??rwise> </choose> </where></select>在上(′ω`*)述示例中,當傳入的參數中包含usernam(′▽?zhuān)?)e且不為空字符串時(shí),會(huì )添加AND username = #{ usernヽ(′ー`)ノame}的條件;當傳入的參數中包含age且不為null時(shí),會(huì )添加AND age = #{ age}的條件;否則,會(huì )執行默認條??件。
問(wèn)題1:如何在MyBatis中使用動(dòng)態(tài)SQL實(shí)現模糊查詢(xún)?
解答:可以使用<if>標簽結合like關(guān)鍵字實(shí)現模糊查詢(xún)。
<select id="findUsersByName" parameterType=&(′?_?`)quot;(′Д` )map"ヽ(′▽?zhuān)?ノ; resultType="??;User"> SELECT * FROM user <where> <if test=&??quot;nヽ(′▽?zhuān)?ノame != null and name != ''"> AND name LIKE '%${ name}%' </if> </where??></select>??;在上述示例中,如果傳入的參(can)數中包含name且不為空字符串,則會(huì )添加AND name LIKE ‘%${ name}%’的條件,實(shí)現模糊查詢(xún)。%表示匹配任意字符序列。
問(wèn)題2:如何在MyBatis中使用動(dòng)態(tài)SQL實(shí)現排序?
<select id=&qu??ot;findUsersOrderByAge" parameterType="map" resultType="User"> SELECT * FROM user <(′?_?`)order by?? property="age" order="(◎_◎;)desc(′?_?`)&q(????)uot;/></select>
在上述示例中,會(huì )??根據傳入的參(can)數中的age字段進(jìn)行降序排序,property指定排序字段為age,order指定排序方式為desc(降序),可以根據需要修改屬性值來(lái)實(shí)現不同的排序效果。