mybatis中的where

在多个查询条件下,由于需要拼接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>
原文地址:https://www.cnblogs.com/tdyang/p/12745006.html