mybatis標簽之——


trim標記是一個格式化的標記,主要用於拼接sql的條件語句(前綴或后綴的添加或忽略),可以完成set或者是where標記的功能。

trim屬性主要有以下四個

  •  prefix:前綴覆蓋並增加其內容
  •  suffix:后綴覆蓋並增加其內容
  •  prefixOverrides:前綴判斷的條件
  •  suffixOverrides:后綴判斷的條件

例如在update中

<update id="updateByPrimaryKey" parameterType="Object">
        update student set 
  <trim  suffixOverrides="," > 
    <if test="name != null  ">
        NAME=#{name},
    </if>
    <if test="hobby != null  ">
        HOBBY=#{hobby},
    </if>
  </trim> where id=#{id}
    </update>

 如果name和hobby的值都不為空的話,會執行如下語句

update student set NAME='XX',HOBBY='XX' /*,*/ where id='XX'

會忽略最后一個“,” ;

在select中

<select id="selectByNameOrHobby" resultMap="BaseResultMap">
select * from student 
<trim prefix="WHERE" prefixOverrides="AND | OR">
    <if test="name != null and name.length()>0"> AND name=#{name}
    </if>
    <if test="hobby != null and hobby.length()>0"> AND hobby=#{hobby}
    </if>
</trim>
</select>

 如果name和hobby的值都不為空的話,會執行如下語句

select * from user WHERE /*and*/ name = ‘xx’ and hobby= ‘xx’

會為<trim>片段添加 "WHERE" 前綴,並忽略第一個 “and”  ;

當然,避免出現“WHERE AND”還有其他方法,如下

<!--將where提取出來,並加上“1=1”的查詢條件 -->
select * from student 
where 1=1
<trim suffixOverrides=",">
   <if test="name != null and name != ''">
      and NAME = #{name}
   </if>
   <if test="hobby != null and hobby != ''">
      and HOBBY = #{hobby}
   </if> 
</trim>

用在insert中

    <insert id="insert" parameterType="Object">
        insert into student    <trim     prefix="("    suffix=")"    suffixOverrides="," >
    <if test="name != null  ">
        NAME,
    </if>
    <if test="hobby != null  ">
        HOBBY,
    </if>    
    </trim>    <trim     prefix="values("    suffix=")"    suffixOverrides="," >  
    <if test="name != null  ">
        #{name},
    </if>
    <if test="hobby != null  ">
        #{hobby},
    </if>
    </trim>
    </insert>

可以為生成格式正確的insert語句。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM