MyBatis Otherwise Tag: Usage Guide

In MyBatis, the tag is often combined with the tag to define the default processing logic when none of the tags meet the conditions. An example is shown below:

<select id="findUserById" resultType="User" parameterType="int">
    SELECT * FROM user
    WHERE id = #{id}
    <choose>
        <when test="id != null">
            AND id = #{id}
        </when>
        <when test="username != null">
            AND username = #{username}
        </when>
        <otherwise>
            AND status = 1
        </otherwise>
    </choose>
</select>

In the example above, if the passed parameter is neither id nor username, the logic inside the tag will be executed, which is to query users with a status of 1.

bannerAds