MyBatis 专题
您的位置:java > MyBatis专题 > Mybatis trim标签
Mybatis trim标签
作者:--    发布时间:2019-11-20 00:47:29

trim代替where/set标签

trim 是更灵活用来去处多余关键字的标签,它可以用来实现 where 和 set 的效果。

<!-- 使用 if/trim 代替 where(判断参数) - 将 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(判断参数) - 将 user 类不为空的属性更新 -->  
<update id="updateuser_if_trim" parametertype="com.h3.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 (对包含的内容加上 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 元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是 prefix 和 suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是 prefixoverrides 和 suffixoverrides;正因为 trim 有这样的功能,所以我们也可以非常简单的利用 trim 来代替 where 元素的功能。



网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册