MyBatis案例:动态条件查询

MyBatis案例:动态条件查询

Bug: 用户必须输入所有的查询条件,才能查询出结果。不够灵活。
SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL

MyBatis对动态SQL有很强大的支撑:

<!--SQL映射文件中的部分代码,多条件查询语句的配置-->
<!--
        动态条件查询
            * if: 条件判断
                * test: 逻辑表达式
            * 问题:
                * 恒等式过度
                * <where> 替换 where 关键字

    -->
    <!--<select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        where 1 = 1
        <if test="status != null">
            and status = #{status}
        </if>
        <if test="companyName != null and companyName != ''">
            and company_name like #{companyName}
        </if>
        <if test="brandName != null and brandName != ''">
            and brand_name like #{brandName}
        </if>

    </select>-->

    <select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        -- where 1 = 1
        <where>
            <if test="status != null">
                and status = #{status}
            </if>
            <if test="companyName != null and companyName != ''">
                and company_name like #{companyName}
            </if>
            <if test="brandName != null and brandName != ''">
                and brand_name like #{brandName}
            </if>

        </where>

    </select>