在多个查询条件下,由于需要拼接sql语句,所以会在前面加上 where 1 = 1

   select id,name,gender,email from emp
        where 1 = 1
            <if test="id != null and id != ''">
                 and id =  #{id}
            </if>
           <if test="name != null and name != ''">
                and name = #{name}
           </if>
    </select>

 可以使用<where></where>代替:

 select id,name,gender,email from emp
       <where>
           <if test="id != null and id != ''">
               and id = #{id}
           </if>
           <if test="name != null and name != ''">
               and name = #{name}
           </if>
       </where>

还可以使用<trim></trim>代替:

trim标签:

1》prefix="":前缀:trim标签体中是整个字符串拼串 后的结果,prefix给拼串后的整个字符串加一个前缀
2》prefixOverrides="":前缀覆盖: 去掉整个字符串前面多余的字符
3》suffix="":后缀,suffix给拼串后的整个字符串加一个后缀
4》suffixOverrides=""后缀覆盖:去掉整个字符串后面多余的字符

  select id,name,gender,email from emp
       <trim prefix="where" prefixOverrides="and">
           <if test="id != null and id != ''">
               and id =  #{id}
           </if>
           <if test="name != null and name != ''">
               and name = #{name}
           </if>
       </trim>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐