2.<if> 标签
<select id="selectTest" resultType="bean.TestBean" parameterType="bean.TestBean">
select * from test where
<if test="id!=null"> <!-- test="id!=null" 这里的 id 值是调用了parameterType参数的 getId()方法获取的 -->
<!-- 所以参数不能是基本类型(因为基本类型和包装类没有 get()方法) -->
id=#{id} <!-- 如果 id 不等于 null ,这段sql语句变成如下所示-->
</if> <!-- select * from test where id=#{id} or id=1 -->
or id=1 <!-- 如果 id 等于 null(即 参数.getId() == null) ,那么语句这段sql语句变成如下所示 -->
<!-- select * from where or id=1 报错!,这时候要用 <where> 标签防止这种情况发生 -->
</select>
3.<where>标签
案例1
<select id="selectTest" resultType="bean.TestBean" parameterType="bean.TestBean">
select * from test
<where> <!-- 使用<where>标签后,如果where后面紧跟着的是 or 和 and ,那么这两个关键字会被忽视-->
<if test="id!=null"> <!-- 例如id等于null 那么这段代码变成 select * from where id=1 sql语句正常-->
id=#{id}
</if>
or id=1
</where>
</select>
案例2
<select id="selectTest" resultType="bean.TestBean" parameterType="bean.TestBean">
select * from test
<where>
or id=1 <!-- or 被忽视,正常运行 -->
</where> <!-- 接下来要讲的是<trim>标签,它能定义<where>的过滤规则 -->
</select>
4.<trim>标签
<select id="selectTest" resultType="bean.TestBean"parameterType="bean.TestBean">
select * from test
<trim prefix="where" prefixOverrides="and |or |abc "> <!-- 这段代码的效果个上面的案例2效果一模一样 -->
abc id=1 <!-- prefixOverrides:前缀覆盖-->
</trim> <!-- 也就是说,where的后面紧跟着的是 and\or\abc,那么这些关键字都会被忽略 -->
</select> <!-- 要注意 | 后面不能有空格,例如: |a 和| a 后面这个a和|之间有空格,会导致忽略失败 -->
5.<set>标签
案例1
<update id="updateTest" parameterType="bean.TestBean">
update test set
<if test="name!=null">
name=#{name},
</if>
<if test="sal!=null">
sal=#{sal}
</if>
where id=#{id}
</update>
<!-- 上面这段代码,还没有使用<set>标签,这段代码有个漏洞,如果 name!=null ,且 sal==null ,那么语句变成-->
<!-- update test set name=#{name}, where id=#{id} -->
<!-- 这里的逗号跟着写进来了,程序理所当然的报错,这时候我们就要用到<set>标签解决这个问题 --
案例2
<update id="updateTest" parameterType="bean.TestBean">
update test
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="sal!=null">
sal=#{sal}
</if>
</set>
where id=#{id}
</update>
<!-- <set>标签和<where>标签有点相反的意思,<set>标签定义了会忽视最后的逗号 “,” 例如<set> name=#{name},</set>里面,最后的是“,”结尾,所以被忽视了,程序正常运行-->
<!-- 当然,<trim>标签同样可以定义<set>标签的规则,下面案例可以看到 -->
案例3
<update id="updateTest" parameterType="bean.TestBean">
update test
<trim prefix="SET" suffixOverrides=", |abc">
<if test="name!=null">
name=#{name},
</if>
<if test="sal!=null">
sal=#{sal}abc
</if>
</trim>
where id=#{id}
</update>
<!-- 使用<trim>定义<set>规则 -->
<!-- suffixOverrides=", |abc",定义了无论是逗号","结尾还是"abc"结尾,都会被程序忽视,上面程序正常运行 -->
<!-- 文中的abc规则是我添加的,原本只有过滤逗号"," -->
choose(when, otherwise)
有时我们不想应用所有的条件, 相反我们想选择很多情况下的一种。Java 中的switch和语句相似,MyBatis提供choose元素。
我们使用上面的示例,但是现在我们来搜索当title提供时仅有title 条件,当author提 供时仅有author条件。如果二者都没提供,只返回featured blogs。
<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>