MyBatis——案例——查询-多条件查询-动态条件查询(关键字 if where)
动态条件查询
SQL语句会随着用户的输入或外部条件的变化而变化,我们称为 动态SQL
MyBatis 对动态SQL有很强大的支撑:
if
choose(when,otherwise)
trim
foreach
将之前的多条件查询改进(之前不能搜索到空字符串以及null)
新增 if 判断(当其中内容满足时才将判断条件加入SQL语句中)
<!-- 动态条件查询 -->
<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="brand_name != null and brand_name != ''">
            and brand_name like #{brand_name}
       </if>
</select>
存在问题,当 status 为 null 时,第一个sql语句判断条件不生效,而后面两个连接上之后存在 and 存在sql语法错误 会报错
解决:
使用 where 标签 替换 where 关键字,<where>标签会自动识别 and 是否在第一位,在第一位就会将其删除

                
            
        
浙公网安备 33010602011771号