1、if
查询语句自带where固定条件的情况下用;
正确示例:
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
错误示例:在3把 where 标签也变成动态的了
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
2、choose, when, otherwise
choose相当于switch,when = case,otherwise = default。同样要注意是否有固定的where条件
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
3、trim, where, set
where标签:
元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
set标签 - 用于update语句:
会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号。
<update id="updateAuthorIfNecessary"> 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} </update>
trim标签可以自定义类似上面 where和set语句;
prefix - 如果if至少有一个满足拼接定义的前缀
prefixOverrides - 移除指定的前缀
suffix - 如果if至少有一个满足拼接定义的后缀
suffixOverrides - 移除指定的后缀
4、foreach
动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
5、代码片段
通过<sql>标签可以定义一个通用的sql代码;<include>去使用代码片段;
注意事项:最好基于单表来定义SQL片段
不要存在where标签
<sql id="allParams" > <if test="id > 0"> and id = #{id} </if> </sql> <select id="getList" resultMap="teacherStudent"> select * from mybatis.teacher <where> <include refid="allParams"></include> </where> </select>