动态SQL之标签

本节主要讲了动态SQL的几个标签:where set trim

where: 检出where语句的最前面是否含有AND和一个空格 或者 or和一个空格 ,如果有的话删除

set: 检出set的最后是否有逗号 ,如果有,则清空

trim:可用来替换where和set

foreach:遍历集合(array,list,key)

CDATA:不支持标签,用于有<等需要&lt;时

where 和 if 条件查询

<select id="whereMore01" resultType="com.shxt.model.User">
  SELECT
  *
  FROM user
  <where>
    <if test="user_name!=null and user_name.length() >0">
      AND user_name like CONCAT(#{user_name},'%')
    </if>
    <!-- &amp;&amp; 不推荐记忆 &lt;< -->
    <if test="account!=null and account.length() > 0">
      AND account = #{account}
    </if>
    </where>
</select>

set 和 if 更新对象信息

<update id="update01" parameterType="com.shxt.model.User" >
  UPDATE user
  <set>
    <if test="account!=null">
      account =#{account},
    </if>
    <if test="password!=null">
      password = #{password},
    </if>
    <if test="user_name!=null">
      user_name =#{user_name},
    </if>

  </set>
  WHERE
  id = #{id}
</update>

trim替换

  替换条件查询where

<select id="whereMore02" resultType="com.shxt.model.User">
  SELECT
  *
  FROM user
  <trim prefix="WHERE" prefixOverrides="AND |OR ">
    <if test="user_name!=null and user_name.length() >0">
      AND user_name like CONCAT(#{user_name},'%')
    </if>
    <!-- &amp;&amp; 不推荐记忆 &lt;< -->
    <if test="account!=null and account.length() > 0">
      AND account = #{account}
    </if>
  </trim>
</select>

  替换更新操作set

<update id="update02" parameterType="com.shxt.model.User" >
  UPDATE user
  <trim prefix="set" suffixOverrides=",">
    <if test="account!=null">
      account =#{account},
    </if>
    <if test="password!=null">
      password = #{password},
    </if>
    <if test="user_name!=null">
      user_name =#{user_name},
    </if>
  </trim>
  WHERE
  id = #{id}
</update>

foreach遍历in(2,3,4,5)

<select id="collectionTest" resultType="User">

  select * from user where id in

  <foreach collection="list|array|key" index = "index" item="us" open="(" close=")" separator=",">

     #{us}

  </foreach>

</select>

CDATA:查询小于id的集合

  <![CDATA[

    select * from user where id < #{id}

  ]]>

posted @ 2016-06-10 16:26  菜包包  阅读(264)  评论(0编辑  收藏  举报