目录
动态SQL是MyBatis的一个强大特性,可以运用动态SQL语句标签方便我们在SQL中实现各种逻辑
1.<if>标签
<select id="selectUser" resultType="User">
select * from user
<if test="username!='' and username!=null">
where username=#{username}
</if>
</select>
2.<where>标签
只使用if会有缺点
<select id="selectUser" resultType="User">
select * from user
where
<if test="username!='' and username!=null">
username=#{username}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</select>
用where可以避免
<select id="selectUser" resultType="User">
select * from user
<where>
<if test="username!='' and username!=null">
and username=#{username}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</where>
</select>
智能识别多余的and和where,保证构造SQL的语法正确
3.<choose>标签
<select id="selectUser" resultType="User">
select * from user
<where>
<choose>
<when test="username!='' and username!=null">
and username=#{username}
</when>
<when test="sex!=null">
and sex=#{sex}
</when>
</choose>
</where>
</select>
4.<set>标签
只用if同where标签一样,没有username会出现SQL语句错误
<update id="updateUser" resultType="string">
update user
set
<if test="username!='' and username!=null">
username=#{username}
</if>
<if test="sex!=null">
,sex=#{sex}
</if>
where id=#{id}
</update>
使用<set>标签
<update id="updateUser" resultType="string">
update user
<set>
<if test="username!='' and username!=null">
,username=#{username}
</if>
<if test="sex!=null">
,sex=#{sex}
</if>
</set>
where id=#{id}
</update>
set标签可以智能的处理更新语句中的逗号
5.<trim>标签(自由)
trim标签:可用于拼接动态SQL语句
该标签有以下属性:
prefix:前缀
suffix:后缀
prefixOverrides:前缀覆盖,可用于智能的处理”and”,”or”关键字
suffixOverrides:后缀覆盖,可用于处理update语句中中多余的”,”
作用:可以利用trim来代替<where>或者<set>的功能
使用trim代替where
使用trim代替set
<update id="updateUser" resultType="string">
update user
<trim prefix="set" prefixOverrides=",">
<if test="username!='' and username!=null">
,username=#{username}
</if>
<if test="sex!=null">
,sex=#{sex}
</if>
</set>
where id=#{id}
</update>
6.<foreach>标签
foreach标签可以在SQL语句中迭代一个集合,常用于构造sql中in条件
foreach标签的属性主要有 item,index,collection,open,separator,close。
item:表示对集合进行迭代时每一个对象的别名。
index:指定一个名字,用于表示在迭代过程中,每次迭代的位置open是前缀,表示该语句以什么开始。
separator:表示在每次迭代元素之间以什么符号作为分隔符。
close:是后缀,表示以什么结束。
collection:指定需要遍历的集合。
<select id="selectStudentById" resultType="Uer">
select * from user
where id in
<foreach collection="list"
item="stu"
open="("
close=")"
separator=",">
#{stu}
</foreach>
</select>