Mybatis Otherwise详解

发布时间:2023-05-23

Mybatis是一个开源的ORM框架,它提供了一个优雅的方式来绑定自定义SQL查询和数据库操作。在Mybatis的SQL映射文件中,通过标签的方式来定义SQL语句,其中otherwise是一个非常有用的标签。在本文中,我们将从多个方面,对Mybatis的otherwise进行详细的阐述。

一、Mybatis Otherwise标签介绍

Mybatis的otherwise标签是在choose标签之中使用,它的作用是在choose标签中没有一个when标签能匹配时,提供一个默认情况下的处理方式。

<choose>
  <when test="condition1">
    <select id="selectUsers1" resultType="User">
      select * from users where id = #{id}
    </select>
  </when>
  <when test="condition2">
    <select id="selectUsers2" resultType="User">
      select * from users where name = #{name}
    </select>
  </when>
  <otherwise>
    <select id="selectUsers3" resultType="User">
      select * from users
    </select>
  </otherwise>
</choose>

以上的代码是一个choose语句块,由于有otherwise标签,它就相当于是一个switch/case语句块,如果条件condition1和condition2都不满足,则会执行otherwise标签内定义的SQL语句。

二、Mybatis Otherwise使用场景

下面我们来看一个使用场景: 假设我们查询用户的性别,当用户的性别是男性的时候,查询tb_man_info表;当用户的性别是女性的时候,查询tb_woman_info表;当用户的性别不明确时,我们需要查询所有的表。

<select id="getUserInfo" resultMap="userInfo">
  SELECT u.*,
    <choose>
      <when test="gender == 'male'">
        mi.man_age age, mi.man_work work
      </when>
      <when test="gender == 'female'">
        wi.woman_age age, wi.woman_work work
      </when>
      <otherwise>
        ''
      </otherwise>
    </choose>
  FROM tb_user u
  <choose>
    <when test="gender == 'male'">
      LEFT JOIN tb_man_info mi ON mi.user_id=u.id
    </when>
    <when test="gender == 'female'">
      LEFT JOIN tb_woman_info wi ON wi.user_id=u.id
    </when>
    <otherwise>
      LEFT JOIN tb_man_info mi ON mi.user_id=u.id
      LEFT JOIN tb_woman_info wi ON wi.user_id=u.id
    </otherwise>
  </choose>
</select>

在以上的SQL语句中,当用户的性别是男性或女性的时候,我们分别在tb_man_info和tb_woman_info表中查询相关信息。当用户的性别不明确时,我们需要查询所有的表。 可以看到,otherwise标签非常有用,它帮助我们定义了当choose内的when语句全都不满足时的情况。

三、Mybatis Otherwise注意事项

  1. Mybatis的otherwise标签一定要放在最后,否则会抛出异常;
  2. Mybatis的otherwise标签内必须书写SQL语句或者任何其他的Mybatis标签。

四、本文总结

本文从Mybatis Otherwise标签的介绍、使用场景以及注意事项进行了详尽的介绍。otherwise标签是Mybatis中非常重要的一个标签,它帮助我们处理choose内的when全都不满足时的情况。