mybatis 动态sql 的一些应用
在项目中常用的查询,会有不同条件,不同的选择,见过分别将这些条件写成if,然后每个if对应一条sql。这样效率低,代码逻辑比较复杂 如果有三种条件组合就有8种情况。坑啊
应用mybatis动态sql能有效减少这类if的使用
MyBatis常用于动态sql的有
if
chosen(when ,otherwise)
tirm
where
set
foreach
if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。(不存在else )
WHERE o.business_type in ( -10000 <if test="param.cellCharge == true"> ,2 </if> <if test= "param.balanceCharge == true"> ,6 </if> <if test= "param.balanceWithDraw == true"> ,7 </if> <if test="param.balanceWithDraw == false and param.balanceCharge == false and param.cellCharge == false"> ,2,6,7 </if>
注意if中会出现都没有的情况,需要添加一些语句,以保证在没有条件符合时,动态生成的sql任然是正确的。
choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。看如下一个例子:
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog"> 02 select * from t_blog where 1 = 1 03 <choose> 04 05 <when test="title != null"> 06 and title = #{title} 07 </when> 08 <when test="content != null"> 09 and content = #{content} 10 </when> 11 <otherwise> 12 13 and owner = "owner1" 14 </otherwise> 15 </choose> 16 </select>
choose中只执行一种情况或者都不执行,相当于java中的switch。不同的是:当when中有条件满足的时候,就会跳出choose
即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。
where
<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog"> 02 select * from t_blog 03 <where> 04 <if test="title != null"> 05 title = #{title} 06 </if> 07 <if test="content != null"> 08 09 and content = #{content} 10 </if> 11 <if test="owner != null"> 12 and owner = #{owner} 13 </if> 14 </where> 15 </select>
- where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;此外,在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上。像上述例子中,如果title=null, 而content != null,那么输出的整个语句会是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或 or 给忽略。
set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:
<update id="dynamicSetTest" parameterType="Blog"> 02 update t_blog 03 <set> 04 <if test="title != null"> 05 title = #{title}, 06 </if> 07 <if test="content != null"> 08 09 content = #{content}, 10 </if> 11 <if test="owner != null"> 12 owner = #{owner} 13 </if> 14 </set> 15 where id = #{id} 16 </update>