动态sql
if
动态 SQL 最常见情景是根据条件包含 where 子句的一部分
如果不传入 “userName,pwd”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “userName,pwd” 参数,那么就会对 “userName,pwd” 一列进行模糊查找并返回对应的 BLOG 结果
<select id="getAllUser1" resultType="pojo.User" parameterType="pojo.User">
select * from user where 1=1
<if test="userName!=null">
and userName=#{userName}
</if>
<if test="pwd!=null">
and pwd=#{pwd}
</if>
</select>
choose,when,otherwise
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句
<select id="findActiveUserLike" resultType="pojo.User">
SELECT * FROM User WHERE 1=1
<choose>
<when test="userName != null">
AND userName like #{userName}
</when>
<when test="pwd != null">
AND pwd like #{pwd}
</when>
<otherwise>
AND roleid = 1
</otherwise>
</choose>
</select>
trim
子句的开头为 “AND” 或 “OR” trim会把他们去除,where 元素也会将它们去除。
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
set
set 元素可以用于动态包含需要更新的列,忽略其它不更新的列
<update id="updateset" parameterType="pojo.User">
update user
<set>
<if test="userName!=null">userName=#{userName},</if>
<if test="pwd!=null">pwd=#{pwd}</if>
</set>
where id =#{id}
</update>
foreach
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<select id="getAllUser3" resultType="pojo.User" parameterType="java.util.List">
select * from user where userName in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
where
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句
<select id="getAllUser2" resultType="pojo.User" parameterType="pojo.User">
select * from user
<where>
<if test="userName!=null">
userName=#{userName}
</if>
<if test="pwd!=null">
and pwd=#{pwd}
</if>
</where>
</select>
script
在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素
@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(Author author);
bind
允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>