mybatis的动态SQL(三)where、set、trim标签的使用

上一篇博客我们简单的介绍了一下choose when otherwise的用法,这一篇我们来聊聊另外当个差不多的标签的用法:where、set、trim

1. where标签的作用:如果该标签包含的元素中有返回值,就插入一个where;如果where后面的字符是以AND和OR开头的,就讲他们剔除

举个例子:

<select id="selectByUser" resultType="cd.mybatis.simple.model.SysUser">
        select id,
        user_name userName,
        user_password userPassWord,
        user_email userEmail,
        user_info userInfo,
        user_img headImg,
        create_time createTime
    from sys_user
    where 1=1
        <if test="userName != null and userName !=''">
            and user_name like concat('%',#{userName},'%')
        </if>
        <if test="userEmail !=''and userEmail !=null">
            and user_email=#{userEmail}
        </if>
    </select>

使用where标签修改后:

<select id="selectByUser" resultType="tk.mybatis.simple.model.SysUser">
        select id,
        user_name userName,
        user_password userPassWord,
        user_email userEmail,
        user_info userInfo,
        user_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 !=''and userEmail !=null">
            and user_email=#{userEmail}
        </if>
    </where>
    </select>

第一个例子中,如果没有where1=1,当两个if条件都不满足时,最后生成的SQL就会以where结束,这样不符合SQL规范,所以需要加一个默认为true的条件

第二个例子,如果两个if条件不满足的时候,where标签包着的这一段代码就会被剔除掉,在SQL中就不会出现这一段代码了

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

举个例子:

<!--批量更新学生信息-XX-2017-7-24 17:00:08-->
    <update id="updateStudentList">
        <foreach collection="studentEntitys" item="item" index="index" open="" close="" separator=";">
            update t_student
            <set>
                <if test="item.classesId!='' and item.classesId!=null">
                    classes_id=${item.classesId}
                </if>
                <if test="item.code!='' and item.code!=null">
                    code=${item.code}
                </if>
                <if test="item.roomId!='' and item.roomId!=null">
                    room_id=${item.roomId}
                </if>
            </set>
            where id = ${item.id}
        </foreach>
    </update>

注意最后的where id=${item.id} 是不可省略的,如果set包含的内容为空,只能避免最后遗留的逗号问题

3.trim用法:where和set标签的功能都可以使用trim标签来实现,并且在底层就是通过TrimSqlNode实现的

where标签对应的trim实现:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>

set标签对应的trim实现:

<trim prefix="SET" prefixOverrides=",">
...
</trim>

trim属性

  • prefix:当trim元素内包含内容时,会给内容增加prefix指定前缀
  • prefixOverrides: 当trim元素内包含内容时,会把内容中匹配的前缀字符串去掉
  • suffix: 当trim元素内包含内容时,会给内容增加suffix指定的后缀
  • suffixOverrides:当trim内包含内容时,会把内容中匹配的后缀字符串去掉
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值