zoukankan      html  css  js  c++  java
  • MyBatis中if,where,set标签

    <if>标签 

    <select id="findActiveBlogWithTitleLike"
         resultType="Blog">
      SELECT * FROM BLOG 
      WHERE state = ‘ACTIVE’ 
      <if test="title != null">
        AND title like #{title}
      </if>
    </select>

    if标签通常伴随着where,set出现。当增加查询条件的时候有下面的代码

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG WHERE state = ‘ACTIVE’ 
      <if test="title != null">
        AND title like #{title}
      </if>
      <if test="author != null and author.name != null">
        AND author_name like #{author.name}
      </if>
    </select>

    但是当state属性也需要动态表示的时候则变成

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG 
      WHERE 
      <if test="state != null">
        state = #{state}
      </if> 
      <if test="title != null">
        AND title like #{title}
      </if>
      <if test="author != null and author.name != null">
        AND author_name like #{author.name}
      </if>
    </select>

    此时会出现当state为null时,sql语句会变为 select * from BLOG WHERE AND...解决此问题则引入<where><set>等标签.

    <where>标签

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG 
      <where> 
        <if test="state != null">
             state = #{state}
        </if> 
        <if test="title != null">
            AND title like #{title}
        </if>
        <if test="author != null and author.name != null">
            AND author_name like #{author.name}
        </if>
      </where>
    </select>

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

    如果 where 元素没有按正常套路出牌,我们还是可以通过自定义 trim 元素来定制我们想要的功能。比如,和 where 元素等价的自定义 trim 元素为:

     
    <trim prefix="WHERE" prefixOverrides="AND |OR ">
      ... 
    </trim>

    同理当需要更新数据时使用<set>标签

    <update id="updateAuthorIfNecessary">
      update Author
        <set>
          <if test="username != null">username=#{username},</if>
          <if test="password != null">password=#{password},</if>
          <if test="email != null">email=#{email},</if>
          <if test="bio != null">bio=#{bio}</if>
        </set>
      where id=#{id}
    </update>
  • 相关阅读:
    3、Python文件操作工具 xlwt 工具
    2、Python文件操作工具 xlrd 工具
    1、关于python第三方工具操作xls和xlsx格式的excel文档选型的吐血经历
    设置python的默认编码方式为utf-8
    Python安装第三方库 xlrd 和 xlwt 。处理Excel表格
    I/O字符流
    I/O字节流
    读写锁实现线程安全缓存
    红黑树理解
    Task异常捕获
  • 原文地址:https://www.cnblogs.com/dyc940210/p/7371672.html
Copyright © 2011-2022 走看看