zoukankan      html  css  js  c++  java
  • 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表达式中创建一个变量并将其绑定到上下文。

  • 相关阅读:
    (转)老话题,权限设计及实现!
    (转)深入理解最强桌面地图控件GMAP.NET 百度地图
    (转)一步一步Asp.Net MVC系列_权限管理设计起始篇
    (转)常见存储过程分页PK赛——简单测试分析常见存储过程分页速度
    (转)正则表达之零宽断言(零宽度正预测先行断言)
    holer实现外网访问本地网站
    ural(Timus) 1039. Anniversary Party
    uva 10308 Roads in the North
    其他OJ 树型DP 技能树(未通过)
    ural(Timus) 1067. Disk Tree
  • 原文地址:https://www.cnblogs.com/ZeroMZ/p/11416619.html
Copyright © 2011-2022 走看看