Mybatis中的 switch

我这遇到个问题,如果 type字段为null则查询type is null,否则查对应的值
询问 AI 得知,可以用choose-when-otherwise

<select>
	select * from user
	<where>
		<choose>
			<when test="type != null">and type = #{type}</when>
			<otherwise>and type is null</otherwise>
		</choose>
	</where>
</select>

AI 给出的例子,登录账户时使用username 或者email 或者 手机号

<select id="selectUser" parameterType="map" resultType="com.example.User">
    SELECT * FROM users
    WHERE 
        <choose>
            <when test="username != null and username != ''">
                username = #{username}
            </when>
            <when test="phone != null and phone != ''">
                phone = #{phone}
            </when>
            <otherwise>
                email = #{email}
            </otherwise>
        </choose>
</select>

似乎when可以有很多个并排,但是我没有测试



这是mybatis官方的例子,官网把choose-when-otherwise比作Java的switch-case语句

Sometimes we don’t want all of the conditionals to apply, instead we want to choose only one case among many options. Similar to a switch statement in Java, MyBatis offers a choose element.

Let’s use the example above, but now let’s search only on title if one is provided, then only by author if one is provided. If neither is provided, let’s only return featured blogs (perhaps a strategically list selected by administrators, instead of returning a huge meaningless list of random blogs).

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

突然发现我那个也可以改成

<if test="type == null"> and type is null</if>
<if test="type != null and type != ''"> and type = #{type}</if>

Mybatis 没有if-else,只有if

posted @ 2025-02-20 14:42  echo_lovely  阅读(131)  评论(0)    收藏  举报