动态SQL
什么是动态sql:
就是可以根据条件的不同,执行不同的sql语句,类似于java中的if,for,switch等关键词
而MyBatis也有针对不同情况而选择不同SQL语句的关键词:
if;where;set;choose;Foreach;
他们可以根据传入参数的不同,从而选择不同的SQL语句片段,进行不同的数据库操作。
If语句
if语句的理解可以和java中if语句理解一样,都是满足条件就执行,不满足就不执行。
<select id="selectUser" parameterType="map" resultType="User">
select * from user where
<if test="year != null">
year = #{year}
</if>
<if test="work != null">
and work = #{work}
</if>
</select>
如果你仔细查看便会发现如果year的if语句没有执行,但第二个work的if语句执行了那么sql语句拼接就会变成
select * from user where and work = #{work}
这样的sql语句明显是错误的,这时,另一个语句where就可以帮我们解决这个问题
Where
where标签会知道如果它包含的标签中有返回值的话,它就插入一个where。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。但他不会剔除掉两个sql语句之间连接的AND 或OR
<select id="selectUser" parameterType="map" resultType="User">
select * from user
<where>
<if test="year != null">
year = #{year}
</if>
<if test="work != null">
and work = #{work}
</if>
</where>
</select>
Set
上面两个是关于查询的案例,而关于修改的情况一般会用到set标签
set中
<update id="updateUser" parameterType="map">
update user
<set>
<if test="year != null">
<!-- set中这里需要用逗号来做结尾-->
year = #{year},
</if>
<if test="work != null">
work = #{work}
</if>
</set>
where id = #{id};
</update>
Choose
当我们只想在多个SQL语句中挑选一个使用时,我们就需要用到choose标签,它跟java中switch关键字所代表的含义是一样的
choose标签要和when标签和otherwise标签配合 就像java中switch和case和default的关系
<select id="selectUser" parameterType="map" resultType="user">
select * from user
<where>
<choose>
<when test="year != null">
year = #{year}
</when>
<when test="work != work">
and work = #{work}
</when>
<otherwise>
and wages = #{wages}
</otherwise>
</choose>
</where>
</select>
Foreach语句
Foreach语句就类似于for循环,用来遍历一定范围内,条件符合的字段。
首先需要把所需要属性做成集合list传进map,再由collection取出
<select id="selectUser" parameterType="map" resultType="User">
select * from user
<where>
<!--
select * from user where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
- collection:指定输入对象中的集合属性
- item:每次遍历生成的对象
- open:开始遍历时的拼接字符串
- close:结束时拼接的字符串
- separator:遍历对象之间需要拼接的字符串
SQL片段
我们在定义mapper.xml片段时,经常会用到重复的SQL 语句,非常的费时,MyBatis就提供了一个SQL片段,类似于把一段SQL语句做成模板,需要用时,就引用这个模板即可。
SQL片段不同的mapper也都可以使用,需要提供地址给namespace
创建SQL片段:
<sql id="test">
<if test="year != null">
year = #{year}
</if>
<if test="work != null">
and work = #{work}
</if>
</sql>
使用SQL片段:
<select id="selectUser" parameterType="map" resultType="user">
select * from user
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="test"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>