MyBatis案例:单条件动态查询

MyBatis案例:单条件动态查询

从多个条件中选择一个
choose(when, otherwise): 选择,类似于Java中的switch语句
如下图中选择一个条件进行模糊查询

<!--SQL映射文件中的部分代码,多条件查询语句的配置-->
<!--<select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
        where
        <choose>&lt;!&ndash;相当于switch&ndash;&gt;
            <when test="status != null">
                status = #{status}
            </when>
            <when test="companyName != null and companyName != ''">
                company_name like #{companyName}
            </when>
            <when test="brandName != null and brandName != ''">
                brand_name like #{brandName}
            </when>
            <otherwise>  # 类似于default
                1 = 1
            </otherwise>
        </choose>
    </select>-->

    <select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
--         where
        <where>
            <choose><!--相当于switch-->
                <when test="status != null">-- 相当于case
                    status = #{status}
                </when>
                <when test="companyName != null and companyName != ''">
                    company_name like #{companyName}
                </when>
                <when test="brandName != null and brandName != ''">
                    brand_name like #{brandName}
                </when>
            </choose>
        </where>

    </select>