sql语句的书写中长需要动态的参数以及条件。在Mybatis中,利用动态 SQL可以很方便地根据不同条件拼接SQL语句。
- if标签
<if test="userName!=null">
and user_name like #{userName}
</if>
if标签通过对test内条件进行判断,如果成功执行标签内语句,反之不执行。
- where标签
where 元素只会在至少有一个子元素的条件返回 SQL子句的情况下才去插入“where”子句;
与 if标签嵌套使用如下
<select id="select" resultType="User">
select id,user_name,mobile,address
from user_info
<where>
<if test="userName!=null">
and user_name like #{userName}
</if>
<if test="mobile!=null">
and mobile like #{mobile}
</if>
</where>
</select>
- set标签
set 元素可以用于动态包含需要更新的列,而删掉无关的逗号。
与update标签嵌套使用如下
<update id="update">
update user_info
<set>
<if test="userName!=null">
user_name = #{userName}
</if>
<if test="mobile!=null">
mobile = #{mobile}
</if>
</set>
where id = #{id}
</update>
update语句书写格式:update 表名称 set 列名称 = 新值 where 列名称 = 某值
- foreach
foreach元素用于对一个集合进行遍历,构建 in 条件语句时常用该元素;foreach元素允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量,也允许指定开头与结尾的字符串以及在迭代结果之间放置分隔符。
格式如下
<select id="selectPostIn" resultType="domain.blog.Post">
select * from user_info
WHERE ID in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
例子
<delete id="delete">
delete from user_info where id in
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</delete>