一、動態SQL
根據條件的不同, SQL 語句也會隨之動態的改變. MyBatis中, 提供了一組標簽用於實現動態SQL.
二、 <if>
用於進行條件判斷, test 屬性用於指定判斷條件. 為了拼接條件, 在 SQL 語句后強行添加 1=1 的恆成立條件.
<select id="sel" resultType="user">
select * from t_user where 1=1 <if test="username != null and username != ''">
and username=#{username} </if> <if test="password != null and password != ''">
and password=#{password} </if> </select>
三、<where>
用於管理 where 子句. 有如下功能:
a) 如果沒有條件, 不會生成 where 關鍵字
b) 如果有條件, 會自動添加 where 關鍵字
c) 如果第一個條件中有and, 去除之
1 <select id="sel" resultType="user"> 2 select * from t_user 3 <where> 4 <if test="username != null and username != ''"> 5 and username=#{username} 6 </if> 7 8 <if test="password != null and password != ''"> 9 and password=#{password} 10 </if> 11 </where> 12 </select>