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>
  • 相关阅读:
    年终了,总结一下
    IIS7下安装.net1.1
    CSLA中的连接管理器ConnectionManager
    CSLA.NET权限规则的困惑
    修改 D
    存储过程万能分页 D
    C/S框架WebService架构用户凭证(令牌)解决方案
    C/S系统开发框架 WebService架构负载均衡技术(Load Balancing)
    C# .NET 开发框架 ClassGenerator 源码生成器 (C/S框架网)
    .Net开发框架
  • 原文地址:https://www.cnblogs.com/dyc940210/p/7371672.html
Copyright © 2011-2022 走看看