六步學會mybatis---------第五章:動態sql
阿新 • • 發佈:2020-12-21
1.if標籤
<select id="selPersons" parameterType="Map" resultMap="PersonResultMap"> SELECT * FROM person where 1=1 <if test="name !=null and name != ''"> and p_name = #{name } </if> <if test="age != null"> and p_age > #{age } </if> </select>
test:判斷條件,格式:屬性名 = 值1 and 引數名=值2…
如果是引數map,屬性名就key
如果條件成立,會將if裡的sql拼接上,如果是第一個,會自動去掉and。
測試一下生成的sql
2. where標籤
寫where 1=1,sql很不美觀
用where標籤會自動判斷是否需要加where
<select id="selPersons" parameterType="Map" resultMap="PersonResultMap"> SELECT * FROM person <where> <if test="name !=null and name != ''"> and p_name = #{name } </if> <if test="age != null"> and p_age > #{age } </if> </where> </select>
測試出來的sql,對比一下
3.choose, when, otherwise標籤
<select id="getEmployees" parameterType="Employee" resultMap="baseResultMap"> select * from employee <where> <choose> <when test="name!=null"> and e_name=#{name} </when> <when test="age!=null"> and e_age=#{age} </when> <otherwise> 1=1 </otherwise> </choose> </where> </select>
Ps:不穿透,when中有一個成立,otherwise不執行
4.Set標籤
<update id="updatePerson" parameterType="Person">
update person
<set>
<if test="name != null and name != ''">
p_name = #{name },
</if>
<if test="age != null">
p_age = #{age },
</if>
</set>
<where>
p_id = #{id}
</where>
</update>
自動判斷是否需要拼接set條件。用於update
5.Foreach標籤
用於批量操作
<insert id="addPersons" parameterType="List">
insert into person (p_name,p_age,p_hobby) values
<foreach collection="list" item="person" separator=",">
(#{person.name},#{person.age},#{person.hobby})
</foreach>
</insert>
<delete id="delPersons" parameterType="List">
delete from person where p_id in
<foreach collection="list" item="person" separator="," open="(" close=")">
#{person.id}
</foreach>
</delete>
collection: 集合型別
item:當前項的名字
separator: 分割字元
open:起始字元
close:結束字元