mybatis动态SQL

  有时候静态SQL语句并不能很好的满足我们的业务,我们希望通过一些条件,来构建动态SQL语句

  mybatis对动态SQL提供了一些:<if>  <where> <trim>  <choose>  <when>  <foreach>  <set> 来实现

1、<if>块

<if  test="要判断的内容">

  如果条件成立SQL语句会跟上这里面的内容

</if>

<if test="salary != null">
     and salary > #{salary}
</if>

  

2、<where>块

where 元素,会自动帮我们添加where ,并且去除where 后面的and or

例如下面的代码,如果两个条件都成立的话SQL语句是where xxx = ? and yyy > ?....

如果第一个条件不成立,SQL语句是where yyy > ?.....

<where>

  <if test = "xxx">

    and xxx = #{id}

  </if>

  <if test = "xxx">

    and yyy > #{salary}

  </if>

  ......

</where>

3、<trim>块

trim:用来裁剪字符串用的,有四个属性

prefix:自动添加前缀

prefixOverrides:把前缀后面的内容覆盖掉

suffix:自动添加后缀

suffixOverrides:把后缀前面的内容覆盖掉

    insert into student
        values 
        <trim prefix="(" suffix=")" prefixOverrides="," suffixOverrides=",">
            ,#{id},#{name},
        </trim>

这样我们得到的sql语句就是:insert into student values(#{id},#{name})

trim自动添加()前后缀,并且把(后面的逗号移除,把)前面的逗号移除

如果希望移除多种情况,可以像这样设置:prefixOverrides=",|."

4、<choose>、<when>、<otherwise>块

有点类似于java里面的  switch  case  default

choose =  switch

when   =  case

otherwise  =  default

如果when里面的条件满足,就不会执行后面的when块和otherwise块了

只选择一个,如果when块都不满足,会选择otherwise块

<choose>
          <when test="salary > 10000 ">
                xxxx1
          </when>
          <when test="salary > 5000">
                xxxx2
          </when>
          <otherwise>
                xxxx3
          </otherwise>
</choose>

5、<set>块

<set>:只写一个,会帮我们自动剔除最后的逗号,不会处理控制的情况,不会自动加逗号

一般用在update操作中

<update id="xxx">
        update employee
        values 
        <set>
               <trim prefix="(" suffix=")," suffixOverrides=",">
                   <if test="id != null">
                       id = #{id},
                   </if>
                   <if test="name != null">
                       name = #{name},
                   </if>
               </trim> 
        </set>
        <where>
            eid = #{eid}
        </where>
    </update>

一般搭配一些逻辑一起使用。

6、<foreach>循环

collection属性值:官方说法,所有可以迭代的变量都行

Dao类方法参数类型是List:collection的值可以是:list,参数名(注解@Param声明的名字,arg0...,param1....)

Dao类方法参数类型是Map:collection的值可以是:参数名(注解@Param声明名字,arg0...,param1....),参数名.keys()或参数名.values()

注意:不能填list,map,或collection,item,和index

separator:以什么分隔

open:以什么开始

close:以什么结束

item:给遍历的元素起的别名

index:下标/索引

<update id="xxx">
        insert into employee(username,salary,gender)
        values 
            <foreach collection="empList" item="emp" open="(" separator="," close=")" index="i">
                username = #{username},
                salary = #{salary},
                gender = #{gender}
            </foreach>
 </update>

这样就能生成动态的SQL语句:insert into employee(username,salary,gender)  values(xxx,xxx,xxx),(xxx,xxx,xxx)

open在遍历empList时,先添加一个(,然后等里面的操作执行完成准备遍历下一个时,close会跟上一个),最后separator会补上一个逗号,当是最后一个元素时,不会补逗号

原文地址:https://www.cnblogs.com/liweixml/p/11654960.html