MyBatis where、set、trim标签的用法

1 where用法

<where>标签的作用:如果该便签包含的元素中有返回值,就插入一个where;如果
where后面的字符串是一and或or开头的,就将它们剔除掉。

 案例分析
            当if条件不满足的时候,where元素中没有任何内容,所以SQL中不会出现where,也就
            不存在4.1.1节中的SQL错误的问题。如果if条件满足,where元素的内容就是以and开
            头的条件,where会主动去掉开头的and,这也能保证where条件正确。
                ——很尴尬的一点,这样的化,反倒会将整张表都给查出来。。。

<select id="selectByUser" resultType="tk.mybatis.simple.model.SysUser">
    SELECT id,
    user_name userName,
    user_password userPassword,
    user_email userEmail,
    user_info userInfo,
    head_img headImg,
    create_time createTime
    FROM sys_user
    <where>
        <if test="userName != null and userName != ''">
            AND user_name LIKE CONCAT('%',#{userName},'%')
        </if>
        <if test="userEmail != null and userEmail != ''">
            AND user_email = #{userEmail}
        </if>
    </where>
</select>

2、 set用法

 <set>标签的作用:如果该标签包含的元素中有返回值,就插入一个set;如果set
后面的字符串是以逗号结尾的,就将这个逗号剔除掉。


<update id="updateByIdSelective">
    UPDATE sys_user
    <set>
        <if test="userName != null and userName != ''">
            user_name = #{userName},
        </if>
        <if test="userPassword != null and userPassword != ''">
            user_password = #{userPassword},
        </if>
        <if test="userEmail != null and userEmail != ''">
            user_email = #{userEmail},
        </if>
        <if test="userInfo != null and userInfo != ''">
            user_info = #{userInfo},
        </if>
        <if test="headImg != null">
            head_img = #{headImg,jdbcType=BLOB},
        </if>
        <if test="createTime != null">
            create_time = #{createTime,jdbcType=TIMESTAMP},
        </if>
        id=#{id}
    </set>
    WHERE id=#{id}
</update>

3 trim用法

        <where>和<set>标签都可以用trim标签实现,并且底层就是通过TrimSqlNode实现的
        
        <where>标签对应的trim实现:
            <trim prefix="WHERE" prefixOverride="AND |OR ">
            
        <set>标签对应的trim实现:
            <trim prefix="SET" suffixOverrides=",">
        
        提示:
            prefixOverride中AND和OR后面的空格不能省略,为了避免匹配到andes或
            orders等单词。实际上prefixOverride包含"AND""OR""AND\n""OR\n"
            "AND\r""OR\r""AND\t""OR\t"
            
        <trim>标签属性:
            prefix:当trim元素包含内容时,会给内容增加prefix指定的前缀
            prefixOverride:当trim元素包含内容时,会把内容中匹配的前缀字符串去掉。
            suffix:当trim元素包含内容时,会给内容增加prefix指定的后缀
            suffixOverride:当trim元素包含内容时,会把内容中匹配的后缀字符串去掉。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值