动态SQL
根据不同的条件,生成不同的SQL语句。
本质就是通过不同的关键字标签,对sql语句的拼接。
if
判断语句
<if test="判断条件">
如果条件成立,执行的语句
</if>
choose(when,otherwise)
类似java中的switch语句,选择其中一个语句执行。
when类似case,otherwise类似default。
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
trim(where,set)
trim标签可以自定义where和set元素。
<trim prefix="where或set标签" prefixOverrides="遇到哪些关键字会删除掉,多个关键字用|分开" suffix="后缀" suffixOverrides="删除尾部的关键字">
</trim>
示例:
<trim prefix="where" prefixOverrides="and|or" suffix="," suffixOverrides="and">
</trim>
这段话的意思是:如果标签内有返回值,加上where前缀,删除内部语句额外的and或or关键字前缀;添加逗号后缀,删除额外的and后缀。
where
通常在语句动态语句的外层嵌套where标签。
只有在where标签内有返回值时,才会在语句加上where关键字。
<where>
如果这里的语句由返回值,where标签会自动加上where关键字
如果语句中开头是and和or关键字,会自动删除
</where>
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
如果第一个if生效了,那么第二个if的and不会被删除。
set
同理where,用法相同。
<!--注意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>
给多个字段赋值,每个set之间用都好分隔。
foreach
遍历指定id集合中数据库对应id的数据。
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定输入对象中的集合属性,要遍历的集合
item:每次遍历生成的对象,集合赋值给哪个字段
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
如果没有foreach循环,可以用这要的写法:select * from blog where 1=1 and (id=1 or id=2 or id=3),或者in关键字
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
最后执行的sql语句是这样的:
select * from blog WHERE ( id = ? or id = ? or id = ? )
SQL片段
将sql语句提出来,在使用的地方引用,简化代码,提高复用性。
sql片段中不要加入where。
定义sql片段:id是自定义的唯一标识符
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
用于sql语句:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>