1. 程式人生 > >MyBatis的動態sql小練習,小回顧

MyBatis的動態sql小練習,小回顧

關鍵字if+trim

trim可以去除多餘的關鍵字,是where和set的組合

trim標記是一個格式化的標記,可以完成set或者是where標記的功能,如下程式碼:

<trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim> prefix:在trim標籤內sql語句加上字首。 suffix:在trim標籤內sql語句加上字尾。 suffixOverrides:指定去除多餘的字尾內容,如:suffixOverrides=",",去除trim標籤內sql語句多餘的字尾","。 prefixOverrides:指定去除多餘的字首內容
<select id="select03" resultMap="BaseResultMap">
select * from personDemo
<trim prefix="where"
prefixOverrides="and|or">
//這裡的trim意思是代替where,並且在某個條件下,把多餘的and或者or去掉比如name為空的時候
//第二條age是不是會有個and,這樣sql語句就錯了,這時候prefixOverride就可以把and去掉
//prefixOverrides去掉字首的and 關鍵字
<if test="name !=null and name!=''">
name=#{name}
</if>
<if test="age !=null and age!=''">
and age=#{age}
</if>
<if test="id !=null and id!=''">
and id=#{id}
</if>
</trim>
</select>

<update id="update02" parameterType="com.demo.mybatisdemo.bean.Person">
update personDemo
<trim prefix="set" suffixOverrides=",">
<if test="name != null and name != ''">
name=#{name},
</if>
<if test="age != null and age !=''">
age=#{age}
</if>
</trim>
where id=#{id}
</update>


標籤<choose><when><otherwise>
這個類似於java裡面的switch標籤,首先在choose標籤裡面,加入判斷條件<when>如果有一個when的條件符合,那麼久不執行其他when標籤,假如所有when標籤都不符合,那麼就執行

<otherwise>標籤裡面的內容
<update id="update03" parameterType="com.demo.mybatisdemo.bean.Person">

update personDemo
  <set>
<choose>
<when test="name!=null and name.length>0">
name=#{name}
</when>
<when test="age!=null and age.length>0">
age=#{age}
</when>
<otherwise>
name='BBBBB'
</otherwise>
</choose>
</set>
where id=#{id}
</update>

還有標籤<foreach>,多配合 關鍵字in使用
這個標籤就是迴圈,裡面有collection,item,open,separator,close
collection介面,例如傳入一個數組ids,那麼這個值為array,如果是list,那麼這個值為list
item為傳入的值的名字,如傳入String[] ids 那麼item為ids
open,即開頭拼接的字元
close,結束拼接的字元
separator,中間分割的字元


<select id="select04" resultMap="BaseResultMap">
select * from personDemo where id in

<foreach collection="array" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>

</select>
上面這段SQL打印出來為:select * from personDemo where id in ( ? , ? )