zoukankan      html  css  js  c++  java
  • Mybatis动态sql技术

    MyBatis中常用动态SQL:

    choose when otherwise if  trim where foreach 

    1,<if>元素被用来有条件地嵌入SQL片段,如果测试条件被赋值为true,则相应地SQL片段将会被添加到SQL语句中。

    <select id="searchCourses" parameterType="map" resultMap="CourseResult">
                SELECT * FROM COURSES
                WHERE TUTOR_ID= #{tutorId}
                <if test="courseName != null">
                    AND NAME LIKE #{courseName}
                </if>

      <......>

    </select>

    2,choose,when 和 otherwise 条件(相当于if ,else if,else)

      select * from test where 1 = 1
      <choose>
        <when test="a!= null">
          and a= #{a}
        </when>
        <when test="b!= null">
          and b= #{b}
        </when>
        <otherwise>
          and c = #{c}
        </otherwise>
      </choose>

    3.foreach

      

     4.trim  

      <trim>标签属性:

      •   prefix:当trim元素包含内容时,会给内容增加prefix指定的前缀
      •   prefixOverride:当trim元素包含内容时,会把内容中匹配的前缀字符串去掉。
      •   suffix:当trim元素包含内容时,会给内容增加prefix指定的后缀
      •   suffixOverride:当trim元素包含内容时,会把内容中匹配的后缀字符串去掉。

      <where>和<set>标签都可以用trim标签实现,并且底层就是通过TrimSqlNode实现的。

    5.where(常用于select语句)

      where标签的作用:如果该标签包含的元素中有返回值,就插入一个where;如果where后面的字符是以AND和OR开头的,就讲他们剔除。

      <select id="findUserByWhere" resultType="User">
        SELECT * FROM user
        <where>
        <if test="name != null and name != ''">
          AND name LIKE concat('%', #{name}, '%')
        </if>
        <if test="phone !=null and phone !=''">
          OR phone=#{phone}
        </if>
        </where>
      </select>

    6.set(常用于update语句)

      标签的作用:如果该标签包含的元素中有返回值,就插入一个set;如果set后面的字符串是以逗号结尾的,就将这个逗号剔除。

      <update id="updateUser">
        UPDATE user
      <set>
        <if test="user.email != null and user.email != ''">email=#{user.email},</if>
        <if test="user.phone != null and user.phone != ''">phone=#{user.phone},</if>
      </set>
        WHERE uid=#{user.uid}
      </update>

  • 相关阅读:
    C#文件操作与编程
    C# 中字符串转换成日期
    C#数据类型与数据库字段类型对应
    C# 知识点随手学习网站推荐
    Java -- 线程
    Java -- IO
    Java -- Swing 组件使用
    Java -- 乒乓球 乒乓弹球游戏
    Java -- AWT 画图,图像处理
    Java -- AWT 菜单建立, Menu, 右键菜单
  • 原文地址:https://www.cnblogs.com/nyhhd/p/12592439.html
Copyright © 2011-2022 走看看