mybatis動態sql中where、set、if 、for迴圈使用
阿新 • • 發佈:2018-12-30
where-if
<select id="listBySearch" resultType="java.lang.Integer"> SELECT id FROM hospital <where> <if test="search.province!=null and search.province!=''"> province=#{search.province} </if> <if test="search.city!=null and search.city!=''"> AND city=#{search.city} </if> </where> </select>
test裡面是條件 多個條件用and連線,if外加where標籤後如果第一個if不符合條件,第二個if會自動去掉開頭的 AND (不會去掉結尾的AND)SQL:
SELECT id FROM hospital WHERE city='xxx'
set-if
<update id="updateHospitalById"> UPDATE user <set > <if test="name != null" > name = #{name}, </if> <if test="sex != null" > sex = #{sex}, </if> </set> WHERE type = #{type} </update>
test裡面是條件 多個條件用and連線,if外加set標籤後編譯出來的sql會去掉sex = #{sex},
中的,
,如果條件都滿足則SQL為:
UPDATE user SET name='xxx' ,sex='xxx' WHERE type='xxx'
for
<select id="listByIds" resultType="hospital"> SELECT * FROM hospital <foreach collection="list" item="item" index="index" open="WHERE id IN (" separator="," close=")"> #{item.id} </foreach> </select>
collection:要迴圈的集合
item:當前迭代物件
index:當前迭代次數
open:以什麼字元開始
separator:分割符
close:以什麼結束
如果list 的size為4,id分別為 1,2,3,4則SQL為:
SELECT * FROM hospital WHERE id IN(1,2,3,4)