choose(when,otherwise)
<select id="queryBlogChoose" parameterType="Map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title !=nll">
title=#{title}
</when>
<when test="author != null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
类似switch,case,选择满足的一种情况执行,都满足选择第一条
trim(where,set)
<select id="queryBlogIf" parameterType="Map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
where标签可自动识别if语句是不是第一句从而视情况省略and,避免出现where and 的情况,也不用像上一节写where 1=1。若查询语句后没有特定条件,where也会自动省略。
<update id="updateBlog" parameterType="Map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
set元素会动态前置set关键字,同时也会删掉无关的逗号
所谓的动态SQL,本质还是SQL语句,只是可以在SQL层面,去执行一个逻辑代码