If标签:条件判断
test属性:编写ognl表达式
<select id="queryUsersLikeUserName" resultType="User">
select * from tb_user where sex = 1
<if test="userName!=null and userName.trim()!=''">
and user_name like '%' #{userName} '%'
</if>
</select>
choose标签:条件选择
when子标签:用于条件选择,一旦有一个when成立,后续不再执行。
otherwise子标签:所有条件不成立,执行该条件。
<select id="queryUserListByUserNameOrAge" resultType="User">
select * from tb_user where sex = 1
<choose>
<when test="userName!=null and userName.trim()!=''">
and user_name like '%' #{userName} '%'
</when>
<when test="age!=null">
and age < #{age}
</when>
<otherwise>
and user_name = 'zhangsan'
</otherwise>
</choose>
</select>
where标签:用于sql动态条件拼接,添加where关键字,可以将动态sql多余的第一个and或者or去除。
<select id="queryUserListByUserNameAndAge" resultType="User">
select * from tb_user
<!--
where标签的作用:
1、自动添加where关键字
2、自动去除动态sql前面多余的一个and或者or
-->
<where>
<if test="userName!=null and userName.trim()!=''">
and user_name like '%' #{userName} '%'
</if>
<if test="age!=null">
and age = #{age}
</if>
</where>
</select>
set标签: 用于更新语句的拼接,添加set关键字,并可以将动态sql中多余的逗号去除
<update id="updateUserSelective" parameterType="User">
update tb_user
<set>
<if test="userName!=null and userName.trim()!=''">
user_name = #{userName},
</if>
<if test="password!=null and password.trim()!=''">
password = #{password},
</if>
<if test="name!=null and name.trim()!=''">
name = #{name},
</if>
<if test="age!=null">
age = #{age}
</if>
</set>
where id = #{id}
</update>
foreach标签:用于遍历参数中的集合
collection属性:参数中的集合
item属性:表示集合中的某个元素
separator属性:分隔符
open:以什么开始
close:以什么结束
<select id="queryUserListByIds" resultType="User">
select * from tb_user
<where>
<if test="ids!=null">
<!--
foreach标签:遍历集合
collection属性:接收的集合参数
item属性:集合参数中的每一个元素
separator属性:标签逗号分隔符
open属性:以什么开始
close属性:以什么结束
-->
<foreach collection="ids" item="id" separator="," open="("
close=")">
#{id}
</foreach>
</if>
</where>