**
动态SQL
**
<!--动态sql语句-->
<!--<if></if>标签 判断某个值不为null的时候 自动拼接 sql语句-->
<select id="" resultType="">
/*如果所有的if都没有成立 就执行这句 查找所有*/
SELECT * FROM t_table WHERE 1=1
<if test=" xxx != null ">
/*if语句为true时会在上面的sql语句后面拼接上这一句*/
AND xxx = #{xxx}
</if>
<if test="yyy != null">
/*不成立时 不会拼接*/
AND yyy = #{yyy}
</if>
</select>
<!--但是我们不能在 WHERE 后面加上 1=1 所以有<where></where>标签 并且这个标签会自动 去掉第一个条件的 AND OR-->
<select id="" resultType="">
/*如果所有的if都没有成立 就执行这句 查找所有*/
SELECT * FROM t_table
/*在where标签里面的if如果有成立的 会自动添加一个 WHERE 谈后拼接*/
<where>
<if test=" xxx != null ">
/*if语句为true时会在上面的sql语句后面拼接上这一句 如果这句在最前面 会自动去掉AND*/
AND xxx = #{xxx}
</if>
<if test="yyy != null">
/*不成立时 不会拼接*/
AND yyy = #{yyy}
</if>
</where>
</select>
<!--<choose></choose>标签 在 choose 标签下面的 when 就如同 if 一样 但是只有最先成立的那一个会被拼接
如果都不成立那就走 otherwise 标签里的
-->
<select id="" resultType="">
/*如果所有的if都没有成立 就执行这句 查找所有*/
SELECT * FROM t_table
<where>
<choose>
<when test="xxx != null">
AND xxx = #{xxx}
</when>
<when test="yyy != null">
AND yyy = #{yyy}
</when>
<otherwise>
AND zzz = #{zzz}
</otherwise>
</choose>
</where>
</select>
<!--<set></set>标签会在有条件成立时自动添加 SET 并且会删除没用的逗号 并且不能所有的 if 都不成立
否则sql语句会变成 UPDATE s_table WHERE id = #{id}
-->
<update id="" parameterType="">
UPDATE s_table
<set>
<if test="xxx != xxx">
xxx = #{xxx}, /*如果有多个条件这个逗号必须加 不加会报错*/
</if>
<if test="yyy != yyy">
yyy = #{yyy}, /*如果这个是最后一个 ,那么set标签会自动去掉这个逗号*/
</if>
</set>
WHERE id = #{id}
</update>
<!--trim标签可以修改 where标签 和 set标签 中自动添加和去掉的东西-->
<!--<sql></sql>标签可以提取出一个公共的sql语句片段 实现代码复用-->
<sql id="if-xxx-yyy">
<if test="xxx != null">
xxx = #{xxx}
</if>
<if test="yyy != null">
yyy = #{yyy}
</if>
</sql>
<!--使用 include 标签 引入sql片段-->
<select id="" resultType="" parameterType="">
SELECT * FROM t_table
<where>
<include refid="if-xxx-yyy"></include>
</where>
</select>
<!--<foreach></foreach>标签 传过来一个集合
collection="传过来的集合"
item="集合中的每一个值"
open="开头"
close="结尾"
index="下标"(一般用不着)
separator="分割符(每个值之间的符号)"
-->
<select id="" resultType="" parameterType="">
SELECT * FROM t_table
<where>
<foreach collection="xxxs" item="xxx" open="(" close=")" separator="or">
xxx = #{xxx}
</foreach>
/*假设 xxxs 这个集合的长度是 3 那么最终这条sql语句是
SELECT * FROM t_table WHERE (xxx = {xxx} or xxx = #{xxx} xxx = #{xxx})
如果这个集合是个空的 sql语句是
SELECT * FROM t_table
*/
</where>
</select>
**
在mapper接口中使用动态sql标签
**
使用 script 标签可以在接口上面使用动态sql标签
@Update({"<script>",
"update Author",
" <set>",
" <if test='username != null'>username=#{username},</if>",
" <if test='password != null'>password=#{password},</if>",
" <if test='email != null'>email=#{email},</if>",
" <if test='bio != null'>bio=#{bio}</if>",
" </set>",
"where id=#{id}",
"</script>"})
void updateAuthorValues(Student student);