mybatis使用<choose> <when> 和 <if></if>

<select id = "" resultMap = "">
select * from table
<where>
  <if test="type == 'x1' ">
      and  条件1;
   </if>
  <if test="type == 'x2' ">
    and 条件2;
  </if>
</where>
</select>


或者

<select id = "" resultMap = "">

  select * from table

   <choose>

        <when test=" type == 'x1' '">

              where   条件1;

       </when >

       <when test=" type == 'x2' '">

          where  条件2;

    </when > 

       <otherwise>

         条件3;   // 可以为空

       </otherwise>

   </choose>

   <if test="type == 'x2' ">   //如果除了以上条件外还有判断的条件,放在chose标签外,不用再写where 

    and  条件2;

  </if>

</select>



例子:
<
select id="queryList" resultType="com....."> select * from student WHERE 1=1 <if test="name != null and name != ''"> AND name LIKE concat('%',#{name},'%') </if> <if test="merchantId != null and merchantId != ''"> AND merchant_id =#{merchantId} </if> <choose> <when test="sidx != null and sidx.trim() != ''"> order by ${sidx} ${order} </when> <otherwise> order by id desc </otherwise> </choose>
</select>
原文地址:https://www.cnblogs.com/gjq1126-web/p/12306292.html