配置文件完成动态条件查询

问题:用户输入条件时,是否所有条件都会填写?

解决方案:**SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL。

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

      *if

      *choose(when,otherwise)

      *trim(where)

      *foreach

步骤一:BrandMapper.xml文件中修改查询代码

 

<select id="selectByCondition" resultMap="brandResultMap">
        select  *
        from tb_brand
        where
            <if test="status != null">
                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>

 

Ps.    if语句,询问是否为空值,或者传入空格,如果传入了也可以进行查询,

*if: 条件判断
    *test:逻辑表达式

 

问题:如果出现status(第一个值)值的不匹配情况,也是空值,则会出现问题,第一个条件不需要逻辑运算符

解决方法:1.调整恒等式

在第一个关键字前也添加and,其中  1 = 1  存在是为了符合语法规则,没什么用

 select  *
        from tb_brand
        where 1 = 1
            <if test="status != null">
               and status = #{status}
            </if>

      2.<where> 替换 where关键字,不会出现语法错误

 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>

  *****if:用于判断参数是否有值,使用test属性进行条件判断

    *存在的问题:第一个条件不需要逻辑运算符

    *解决方案:

        1.调整恒等式

        2.<where> 替换 where关键字,不会出现语法错误

  

 

posted @ 2023-03-27 00:53  YE-  阅读(17)  评论(0编辑  收藏  举报