动态SQL
* 什么是动态SQL?
- 动态SQL就是指根据不同的条件,生成不同的SQL语句
- 动态SQL就是在拼接sql语句,将sql语句的拼接规范化,这样更不容易出错。
* 动态sql之 <where> </where>标签
- 使用 <where>标签,Mybatis会识别到,如果传入参数的时候,where条件后没有条件的情况下,会变成where and 条件 这样就会出现语法错误,使用 <where>标签得到话,会自动去掉and关键字。
* 动态SQL之 If 标签
<!--通过IF查询数据-->
<select id="queryBlogIf" parameterType="map" resultType="com.shi.pojo.Blog">
select * from blog where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</select>
* 动态SQL之 choose when otherwise 相当于switch。满足一个条件即可,如果第一个条件满足,那么下边的条件就无效了。
<!--查询语句 Choose-->
<select id="queryBlogChoose" parameterType="Map" resultType="com.shi.pojo.Blog">
select * from blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
* 动态SQL之Set
<!--更新博客数据 使用set-->
<update id="updateBlog" parameterType="Map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author}
</if>
</set>
where id =#{id};
</update>
* 动态SQL之 trim标签 定制化动态标签
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
* 动态SQl之 SQL片段 <sql id="sql片段设置id"></sql> 引用 <include refid="设置的sql片段id"></include>
- 有时候我们需要将一些代码的公共部分提取出来,方便进行代码复用
- 使用<sql>标签抽取公共部分,使用<include>标签进行sql片段的引用。
- 最好基于单表来定义sql片段
- <where>标签不能定义进sql片段
- sql判断更多的应用于if标签
- 代码:
<!--提取SQL片段-->
<sql id="if_title_author">
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
<!--查询数据 IF-->
<select id="queryBlogIf" parameterType="map" resultType="com.shi.pojo.Blog">
select * from blog
<where>
<include refid="if_title_author"></include> //引用上面设定的sql片段
</where>
</select>
* 动态sql之<foreach>标签
- <foreach collection="ids"(集合名) item="id"(集合中每一个元素名) open="and (" (拼接开始部分) close=")" (拼接结束部分) separator="or" (分割部分) >
<!--查询语句 foreach-->
<select id="queryBlogForeach" resultType="com.shi.pojo.Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>