mybatis choose when otherwise

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

例如下面例子,同样把所有可以限制的条件都写上,方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑,我们使用where将choose包起来,放置关键字多于错误。

 

<!--  choose(判断参数) - 按顺序将实体类 User 第一个不为空的属性作为:where条件 -->  
<select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
            </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>

第二种形式:
代码 
  1. <!--  choose(判断参数) - 按顺序将实体类 User 第一个不为空的属性作为:where条件 -->    
  2. <select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">    
  3.     SELECT *    
  4.       FROM User u       
  5.         <choose>    
  6.             <when test="username !=null ">    
  7.              where   u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')    
  8.             </when >    
  9.             <when test="sex != null and sex != '' ">    
  10.              where   AND u.sex = #{sex, jdbcType=INTEGER}    
  11.             </when >    
  12.             <when test="birthday != null ">    
  13.              where   AND u.birthday = #{birthday, jdbcType=DATE}    
  14.             </when >    
  15.             <otherwise>
  16.              where  1=1
  17.             </otherwise>    
  18.         </choose>          
  19. </select>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值