0、動態SQL
使⽤用動態 SQL 可簡化代碼的開發,減少開發者的⼯作量,程序可以⾃動根據業務參數來決定 SQL 的拼接。
1、if 標籤
if 標籤可以自動根據表達式的結果來決定是否將對應的語句添加到 SQL 中,如果條件不成立則不添加, 如果條件成立則添加。
<select id="findByAccount" parameterType="com.entity.Account" resultType="com.entity.Account">
select * from t_account where 1 = 1
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null and username.size != 0">
and username = #{username}
</if>
<if test="password!=null and password.size != 0">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</select>
2、where 標籤
上面 if 標籤中的 1=1 是不是看起來很難受?沒有辦法,它是爲了防止SQL出錯而存在的。爲了解決這個問題,可以使用 where 標籤。where 標籤可以自動判斷是否要刪除語句塊中的 and 關鍵字,如果檢測到 where 直接跟 and 拼接,則自動刪除 and,通常情況下 if 和 where 結合起來使用。
<select id="findByAccount" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<where>
<if test="id!=0">
id = #{id}
<-- 也可以這樣寫: and id = #{id} -->
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</where>
</select>
3、choose 、when 標籤
<select id="findByAccount" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<where>
<choose>
<when test="id!=0">
id = #{id}
</when>
<when test="username!=null">
username = #{username}
</when>
<when test="password!=null">
password = #{password}
</when>
<when test="age!=0">
age = #{age}
</when>
</choose>
</where>
</select>
4、trim 標籤
trim 標籤中的 prefix 和 suffix 屬性會被⽤於⽣成實際的 SQL 語句,會和標籤內部的語句進行拼接,如果語句前後出現了 prefixOverrides 或者 suffixOverrides 屬性中指定的值,MyBatis 框架會⾃動將其刪除。
<select id="findByAccount" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<trim prefix="where" prefixOverrides="and">
<if test="id!=0">
id = #{id}
<-- 這樣寫也是可以的:and id = #{id} -->
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</trim>
</select>
5、set 標籤
set 標籤用於 update 操作,會根據參數選擇⾃動⽣成 SQL 語句。
<update id="update" parameterType="com.entity.Account">
update t_account
<set>
<if test="username!=null">
username = #{username},
</if>
<if test="password!=null">
password = #{password},
</if>
<if test="age!=0">
age = #{age}
</if>
</set>
where id = #{id}
</update>
6、foreach 標籤
foreach 標籤可以迭代生成⼀系列值,這個標籤主要用於 SQL 的 in 語句。
<select id="findByIds" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<where>
<foreach collection="ids" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
<select id="queryByIds" resultMap="studentMap" parameterType="map">
select * from t_account
where id in
<foreach item="item" index="index" collection="idList" open="(" separator="," close=")">
#{item}
</foreach>
</select>