鍍金池/ 教程/ Java/ Mybatis trim標簽
Mybatis表關聯(lián)多對一
MyBatis打印輸出SQL語句
Mybatis表關聯(lián)一對多
mybaits if標簽語句
MyBatis整合Spring MVC
MyBatis動態(tài)SQL語句
MyBatis教程
MyBatis choose(when, otherwise)標簽
Mybatis與Spring集成
MyBatis分頁
MyBatis SqlSessionDaoSupport實例
MyBatis where標簽語句
Mybatis增刪改查(CURD)
Mybatis接口注解
Mybatis trim標簽
Mybatis set標簽
Mybatis 多對多
MyBatis環(huán)境配置及入門

Mybatis trim標簽

trim代替where/set標簽

trim 是更靈活用來去處多余關鍵字的標簽,它可以用來實現(xiàn) where 和 set 的效果。

<!-- 使用 if/trim 代替 where(判斷參數(shù)) - 將 User 類不為空的屬性作為 where 條件 -->  
<select id="getUsertList_if_trim" resultMap="resultMap_User">  
    SELECT * 
      FROM user u
    <trim prefix="WHERE" prefixOverrides="AND|OR">  
        <if test="username !=null ">  
            u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="sex != null and sex != '' ">  
            AND u.sex = #{sex, jdbcType=INTEGER}  
        </if>  
        <if test="birthday != null ">  
            AND u.birthday = #{birthday, jdbcType=DATE}  
        </if>
    </trim>     
</select>  

trim 代替 set

<!-- if/trim代替set(判斷參數(shù)) - 將 User 類不為空的屬性更新 -->  
<update id="updateUser_if_trim" parameterType="com.yiibai.pojo.User">  
    UPDATE user  
    <trim prefix="SET" suffixOverrides=",">  
        <if test="username != null and username != '' ">  
            username = #{username},  
        </if>  
        <if test="sex != null and sex != '' ">  
            sex = #{sex},  
        </if>  
        <if test="birthday != null ">  
            birthday = #{birthday},  
        </if>  
         
    </trim>  
    WHERE user_id = #{user_id}  
</update>  

trim (對包含的內(nèi)容加上 prefix,或者 suffix 等,前綴,后綴)

<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
        select * from t_blog 
        <trim prefix="where" prefixOverrides="and |or">
            <if test="title != null">
                title = #{title}
            </if>
            <if test="content != null">
                and content = #{content}
            </if>
            <if test="owner != null">
                or owner = #{owner}
            </if>
        </trim>
    </select>

trim 元素的主要功能是可以在自己包含的內(nèi)容前加上某些前綴,也可以在其后加上某些后綴,與之對應的屬性是 prefix 和 suffix;可以把包含內(nèi)容的首部某些內(nèi)容覆蓋,即忽略,也可以把尾部的某些內(nèi)容覆蓋,對應的屬性是 prefixOverrides 和 suffixOverrides;正因為 trim 有這樣的功能,所以我們也可以非常簡單的利用 trim 來代替 where 元素的功能。