mybatis动态sql详情

动态SQL是mybatis的强大特性之一,MyBatis的动态SQL是基于OGNL表达式来完成的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
MyBatis中用于实现动态SQL的元素主要有9个,如下所示:

元素说明
<if> 判断语句,用于单分支判断
<choose>(<when>、<otherwise>) 相当于java的switch···case···default语句,用于多分支判断
<where>、<trim>、<set> 辅助元素,用于处理一些SQL拼装、特殊字符问题
<foreach> 循环语句,常用于in语句等列举条件中
<bind> 从ognl表达式中创建一个变量,并将其绑定到上下文,常用于模糊查询的sql中

一、if元素

在mybatis中if是最常用的判断语句,用来进行一些简单的判断,然后进行动态sql的拼接。在使用==的时候需要使用toString()方法,这样更加稳定一些。如下例子所示:

<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">  
    select * from t_blog where 1 = 1  
    <if test="title != null">    <!-- test属性用于条件判断语句中,用于判断真假 -->
        and title = #{title}  
    </if>  
    <if test="content != null">  
        and content = #{content}  
    </if>  
    <if test="index=='1'.toString()">  
        and index= #{index}  
    </if>  
    <if test="owner != null">  
        and owner = #{owner}  
    </if>  
</select>  

二、choose(when,otherwise)元素

这个类似于switch多分支语句。

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">  
    select * from t_blog where 1 = 1   
    <choose>  
        <when test="title != null">  
            and title = #{title}  
        </when>  
        <when test="content != null">  
            and content = #{content}  
        </when>
        <when test="job !=null and jobs !=''"> 
            and jobs like concat('%',#{jobs},'%')    <!--concat('%',#{jobs},'%')用于拼接操作-->
        </when> 
        <otherwise>  
            and owner = "owner1"  
        </otherwise>  
    </choose>  
</select> 

https://www.cnblogs.com/jasonboren/p/11394721.html

posted @ 2021-08-30 11:57  Bonnie_ξ  阅读(58)  评论(0编辑  收藏  举报