在ml映射文件中,除了常见的select|insert|updae|delete 标签之外,还有哪些常用的标签?
其他常用的标签有
- if
- where
- set
- choose(when、otherwise)
- foreach
以上这些标签都是Mybatis提供的动态SQL标签
什么是动态SQL标签
??所谓动态SQL就是指根据不同的条件生成不同的SQL语句,本质上还是SQL,知识我们可以在SQL层面,去执行一个逻辑代码,利用Mybatis的动态SQL,我们可以彻底摆脱根据不同条件拼接SQL语句的这种痛苦。
1、if
<select id="queryBlog" parameterType="map" resultType="Blog">
select * from mybatis.blog where 1=1(在做项目中不可能这么写)
<if test="title != null">
and title = #{title}
</if>
<if test="id != null">
and id=#{id}
</if>
</select>
如果where匹配到的第一个if没有and,则正常执行,如果匹配到的第二个if有and ,而第一个又没有匹配上,则会出现错误:如:where and id =#{ }  所以就引入了where标签:
2、where
where元素只会在子元素中返回任何内容的情况下才会插入“where”子句。而且,若子句的开头为“and”或者“or”,where元素也会将他们去除。 以后只要是写动态SQL就写上标签,反正如果不成立,他也不会加上,加上了反而更加智能。
<select id="queryBlogWh" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="id != null">
and id = #{id}
</if>
</where>
</select>
3、choose
标签的使用跟JSTL基本上是一样的,要和标签连用,如
<where>
<choose>
<when>
<otherwise>
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="id != null" >
id =#{id}
</when>
<when test="title != null">
and title = #{title}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
4、set
set标签是用在update语句中的,他的功能跟where标签的功能差不多。 set元素会动态地在首行插入set关键字,并且会删除额外的逗号
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="id != null">
id = #{id},
</if>
<if test="title !=null">
title = #{title},
</if>
<if test="views != null">
views = #{views}(这里没有)
</if>
</set>
where id = #{id}
</update>
5、sql片段
有些时候我们可能会将一些功能相同的部分抽取出来,方便复用
<sql id="title-id">
<if test="title != null">
title = #{title}
</if>
<if test="id != null">
and id = #{id}
</if>
</sql>
然后我们可以在select标签中导入,如:
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<include refid="title-id"></include>
</where>
</select>
注意:sql片段的使用有几个需要注意的点 1、用法:
- 使用SQL标签抽取公共的部分
- 在需要是一个的地方使用include标签引用即可
2、注意点
- 最好基于单表来定义SQL片段
- 不要存在where标签
6、foreach
动态sql的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建in条件语句的时候使用的
具体用法如下图: 
|