Mybatis-学习笔记(5)动态SQL

1、Mybatis采用功能强大的基于ONGL的表达式来完成动态SQL。

2、ONGL常用的元素有:

  

  1》if

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

   Mybatis中,#{id}表达式获取参数有两种方式:一是从HashMap中获取集合中的property对象;二是从Java Bean中获取property对象。

  2》choose

<choose>
   <when test="id != null">
       and id = #{id}
   </when>
   <when test="loginname != null and password != null">
       and loginname = #{loginname} and password = #{password}
   </when>
   <otherwise>
       and sex = '男'
   </otherwise>
</choose>

  3》where

<where>
          <if test="state != null ">
              state = #{state}
          </if>
          <if test="id != null ">
              and id = #{id}
          </if>
          <if test="loginname != null and password != null">
              and loginname = #{loginname} and password = #{password}
          </if>
</where>

  where元素知道只有在一个以上的if条件有值的情况下才去插入where子句。而且,如果最后的内容是“and”或“or”开头,where元素也知道如何将它们去掉。

   4》set

update tb_employee
        <set>
          <if test="loginname != null">loginname=#{loginname},</if>
          <if test="password != null">password=#{password},</if>
          <if test="name != null">name=#{name},</if>
          <if test="sex != null">sex=#{sex},</if>
          <if test="age != null">age=#{age},</if>
          <if test="phone != null">phone=#{phone},</if>
          <if test="sal != null">sal=#{sal},</if>
          <if test="state != null">state=#{state}</if>
        </set>
where id=#{id}

   set元素可以动态前置set关键字,同时也会消除无关的逗号。

   5》foreach

<select id="selectEmployeeIn" resultType="com.lfy.bean.Emp">
      SELECT *
      FROM tb_employee
      WHERE ID in
      <foreach item="item" index="index" collection="list"
          open="(" separator="," close=")">
            #{item}
      </foreach>
</select>

  该元素主要应用于构建in条件语句。doreach元素的功能非常强大,它允许指定一个集合,声明可以用在元素体内的集合项和索引变量。也可以指定开闭匹配的字符串以及在迭代中间放置分隔符。

   6》bind

<select id="selectEmployeeLikeName"  resultType="com.lfy.bean.Emp">
      <bind name="pattern" value="'%' + _parameter.getName() + '%'" />
          SELECT * FROM tb_employee
          WHERE loginname LIKE #{pattern}
</select>

   bind元素可以从ONGL表达式中创建一个变量并将其绑定到上下文。

原文地址:https://www.cnblogs.com/ZeroMZ/p/11416619.html