MyBatis如何实现if-else if-else

在Mybatis中是没有单独提供if-else if-else这种语法的。不过使用它的choose语法来实现。语法如下:

<choose>
            <when test="params!=null">
                right JOIN
            </when>
            <otherwise>
                LEFT JOIN
            </otherwise>
        </choose>

1.单个if-else使用

<select id="selectXxx" resultType="com.xxx.entity.Xxx">
    SELECT
      *
    FROM
      xxx
    WHERE
      1=1
    <choose>
      <when test="xState == 1">
        AND xName = #{name1}
      </when>
      <otherwise>
        AND xName = #{name2}
      </otherwise>
    </choose>
  </select>

2.多个if-else if-else if-else使用

<select id="selectXxx" resultType="com.xxx.entity.Xxx">
    SELECT
      *
    FROM
      xxx
    
    <where>
	    <choose>
	      <when test="xState == 1">
	        AND xName = #{name1}
	      </when>
	     <when test="xState == 2">
	        AND xName = #{name2}
	      </when>
	      <otherwise>
	        AND xName = #{name3}
	      </otherwise>
	    </choose>
    </where>
  </select>
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis中的if-else语句可以使用<choose>...<when>...<otherwise>...</choose>来表示。在<choose>标签中,可以使用多个<when>标签来表示多个条件判断,最后使用<otherwise>标签来表示其他情况。 举个例子,如果我们在一个查询语句中需要根据不同的条件来动态生成不同的SQL语句,可以使用if-else来实现。在<select>标签的SQL语句中,使用<choose>标签包裹条件判断的逻辑。每个条件判断使用<when>标签表示,例如当xxx不为空时,使用<when>语句来拼接SQL语句中的条件;当xxx为空时,使用<otherwise>语句来拼接SQL语句中的条件。 另外还有一个示例是在插入语句中使用if-else语句。在<insert>标签中,使用<foreach>循环来遍历列表,并使用<trim>标签来拼接SQL语句中的字段和对应的值。在<choose>标签中,使用<when>语句来判断字段的值是否为空,如果不为空,则使用字段的值,如果为空,则使用指定的默认值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [mybatis xml mapper 文件中 if-else 写法](https://blog.csdn.net/aotun7642/article/details/102437909)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值