动态SQL语句

动态SQL语句


if标签
例子:
<select >
             where name like concat('%',#{name},'%')
      </if>        
</select>

where标签
<where>标签会进行自动判断
如果任何条件都不成立,那么就在sql语句里就不会出现where关键字
如果有任何条件成立,会自动去掉多出来的 and 或者 or。
例子:
<select >
            and price > #{price}
        </if>    
    </where>         
</select>

set标签
与where标签类似,在update语句里也会碰到多个字段相关的问题
如果任何条件都不成立,sql语句就不会出现set关键字
如果有任何条件成立,set标签会自动去掉最后一个逗号
<update >price=#{price}</if>
        </set>
         where id=#{id}   
</update>

trim标签
trim 用来定制想要的功能
trim标签可以替换where和set标签:
prefixOverrides:前缀覆盖(去掉多余的前缀)
<trim prefix="where" prefixOverrides="and |or ">
      ... 
</trim>
suffixOverrides:后缀覆盖(去掉多余的后缀)
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
例子:
    <select >price=#{price}</if>
              
        </trim>
         
         where id=#{id}   
    </update>

choose标签:(if else的效果)
Mybatis里面没有else标签,但是可以使用when otherwise标签来达到这样的效果。
任何when条件成立,就进行条件查询,否则就使用otherwise条件查询
例子:
<select >
            and price > #{price}
          </when>                      
            <otherwise>
                and id >1
            </otherwise>
          </choose>
      </where>
</select>

foreach标签
通常用于in 这样的语法里
例子:
    <select >
                    #{item}
                </foreach>
    </select>
调用的时候传入一个list集合的对象为参数

bind标签
就像是对传入的参数做一次字符串拼接,方便后续使用
例子:模糊查询,将传入的name前后拼接上%
        <select />
            select * from   product  where name like #{likename}
        </select>