Mybatis动态SQL--choose when

参考MyBatis choose(when, otherwise)标签

前言:

使用mybatis操作数据库肯定是需要自己书写SQL语句的,这在带来方便(进行SQL优化/定制)的同时也要求我们对mybatis的动态SQL有一定了解.

例如在where子句中进行判断,有时候我们并不想应用所有的条件,而只是想根据现有条件从多个选项中选择一个判断条件(逻辑或的关系)。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件(多个if条件之间是逻辑与的关系)。MyBatis 提供了 choose 元素,choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

栗子

<select id="demoMapper" resultType="java.util.hashMap" parameterType="java.util.hashMap">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  //CONCAT字符串连接函数用于连接两个字符串
            </when >  
            <when test="sex != null and sex != '' "> 
                AND u.sex = #{sex, jdbcType=INTEGER}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{birthday, jdbcType=DATE}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>  

上述的动态SQL相当于:若username不为null

SELECT * FROM User u where u.username LIKE ('%'+?+'%');

若色系不为null或空串

SELECT * FROM User u where u.sex = ?;

若上述两个条件都不满足

SELECT * FROM User u

猜你喜欢

转载自blog.csdn.net/flydoging/article/details/85091809
今日推荐