if標籤
實際業務中,有時候會需要一個參數,有時候需要兩個參數,按照原來的方法,需要寫兩個方法。爲了解決這個mybatis提出了if標籤。
SELECT * FROM
t_user
<where>
<if test="(user.name != null) and (user.name != '')">
AND name=#{user.name}
</if>
<if test="(user.sex) != null and (user.sex) != ''">
AND sex={user.sex}
</if>
where標籤
按照上面的方法寫的話,有一個問題,if標籤中的and關鍵字沒法放,前後都可能報錯。所以提出了where標籤。
能夠自動刪除if標籤中的前and
如果後面的條件不成立,where關鍵字也可以省略。
SELECT * FROM
t_user
<where>
<if test="(user.name != null) and (user.name != '')">
AND name=#{user.name}
</if>
<if test="(user.sex) != null and (user.sex) != ''">
AND sex={user.sex}
</if>
</where>
foreach標籤
foreach應用於通過多個id查詢人
SELECT* FROM t_user where id in (1,2,3)
<select id="findUserByIds" parameterType="cn.hd.param.QueryVo">
<include refid="selectUser"></include>
<where>
id in
<foreach collection="ids"item="id" separator="," open="(" close=")">
#{id}
</foreach>
</where>
</select>
如果參數類型是包裝類,collection的值,包裝類中屬性名保持一致即可。
Item必須寫 給遍歷的元素起名字跟下面的佔位符中的值保持一致。
separator分隔符
open 將遍歷的結果後方加上一個值
如果參數是數組
collection的值必須是array
如果是list集合
Collection中的值必須是list
sql片段
<sql id="selectUser">
SELECT * FROM t_user
</sql>
<include refid="selectUser"></include>
<where>
<if test="(user.name != null) and (user.name != '')">
AND name=#{user.name}
</if>
<if test="(user.sex) != null and (user.sex) != ''">
AND sex={user.sex}
</if>
</where>