mybatis的if,where,choose-when -otherwise标签

1、if-where

<!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 -->

<select id="getPage" resultMap="BaseResultMap" >

    SELECT
    a.*,
    b.category_name,
    c.category_small_name,
    d.specs_model,
    e.production_name1
    FROM
    mda_data_acquisition  a
    LEFT JOIN mda_category        b on a.category_code =b.category_code
    LEFT JOIN mda_category_small  c on a.category_small_code =c.category_small_code
    LEFT JOIN mda_specs_model     d on a.specs_model_code =d.specs_model_code
    LEFT JOIN mda_production     e on a.production_code =e.production_code
    <where>
        <if test="categoryCode != null and categoryCode != ''">
            and  a.category_code = #{categoryCode,jdbcType= VARCHAR}
        </if>
        <if test="categorySmallCode != null and  categorySmallCode != ''">
            and  a.category_small_code = #{categorySmallCode,jdbcType= VARCHAR}
        </if>
        <if test="specsModelCode != null and specsModelCode != ''">
            and  a.specs_model_code LIKE CONCAT('%',#{specsModelCode,jdbcType=VARCHAR},'%')
        </if>
        <if test="modelCode != null and modelCode != ''">
            and  a.model_code LIKE CONCAT('%',#{modelCode,jdbcType=VARCHAR},'%')
        </if>
        <if test="specsModel != null and specsModel != ''">
            and  d.specs_model LIKE CONCAT('%',#{specsModel,jdbcType=VARCHAR},'%')
        </if>
    </where>
</select>

2、choose-when -otherwise 类似于java的switch

因为<if>...</if>并没对应的<else>标签,所以要达到<if>...<else>...</else> </if>的效果,得借助<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值