一、If标签
If标签通常不单独使用,与where或set一起使用
二、Where标签
Where标签自动生成where关键字,在遇到第一个字段是AND或OR时,会做自动去除的处理。
<select id="selectUsers" resultType="Sysuser" parameterType="Sysuser">
select * from sysuser
<where>
<if test="uid!=null">
and uid=#{uid}
</if>
<if test="uname!=null and uname!=''">
and uname=#{uname}
</if>
<if test="uphone!=null and uphone!=''">
and uphone=#{uphone}
</if>
<if test="upwd!=null and upwd!=''">
and upwd=#{upwd}
</if>
<if test="uemail!=null and uemail!=''">
and uemail=#{uemail}
</if>
</where>
order by update_time desc
</select>
三、Set标签、
Set标签用在update标签中,来完成修改SQL语句中的逗号去除。
<update id="updateUserByIdSelective" parameterType="sysuser">
update sysuser
<set>
<if test="uname!=null">
uname=#{uname},
</if>
<if test="uphone!=null and uphone!=''">
uphone=#{uphone},
</if>
<if test="upwd!=null and upwd!=''">
upwd=#{upwd},
</if>
<if test="uemail!=null and uemail!=''">
uemail=#{uemail},
</if>
</set>
where uid=#{uid}
</update>
四、Foreach标签
当需要使用in函数查询时,可以使用foreach语句来拼接字符串
collection – 传递参数类型list/array
index – 循环索引
item – 集合中的元素
open –以什么开始; close – 以什么结束
<insert id="addUsers">
insert into sysuser(uname,upwd,uphone,uemail,rid) values
<foreach collection="array" separator="," item="suser">
(#{suser.uname},#{suser.upwd},#{suser.uphone},#{suser.uemail},#{suser.rid})
</foreach>
</insert>
五、Choose-when-otherwise
Mybatis中的choose标签相当于Java中的switch。
<select id="selectUsersOneCondition" resultType="Sysuser" parameterType="Sysuser">
select * from sysuser
<where>
<choose>
<when test="uid!=null">
uid=#{uid}
</when>
<when test="uname!=null and uname!=''">
uname=#{uname}
</when>
<when test="uphone!=null and uphone!=''">
uphone=#{uphone}
</when>
<otherwise></otherwise>
</choose>
</where>
order by update_time desc
</select>