Mybatis中运用小技巧(四)trim标签的使用

trim元素的主要功能是可以在自己包含的内容钱加上某些前缀,也可以在其后加上某写后缀,与之对应的属性是prefix和suffix;
可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides。以下举例:

1、代码为:
select * from user 
  <trim prefix="WHERE" prefixOverrides="AND |OR">
    <if test="name != null and name.length()>0"> AND name=#{name}</if>
    <if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
  </trim>
假如说name和gender的值都不为null的话,打印的SQL为:
select * from user where name = 'xx' and gender = 'xx'

where后不存在and,这是因为prefixOverrides="AND |OR"代表去掉第一个and或者是or。

2、代码为:
update user
  <trim prefix="set" suffixOverrides="," suffix=" where id = #{id} ">
    <if test="name != null and name.length()>0"> name=#{name} , </if>
    <if test="gender != null and gender.length()>0"> AND gender=#{gender} ,  </if>
  </trim>
假如说name和gender的值都不为null的话,打印的SQL为:
update user set name='xx' , gender='xx' where id='x'

可以参考第一个例子理解。

3、代码为:
<insert id="save" parameterType="NoticeEntity">
        INSERT INTO S_NOTICE 
        <trim prefix="(" suffix=")" suffixOverrides=",">
            ID,
            <if test="title != null">TITLE,</if>
            <if test="content != null">CONTENT,</if>
            <if test="noticeStatus != null">NOTICE_STATUS,</if>
            <if test="createdBy != null">CREATED_BY,</if>
            CREATED_TS,
            <if test="lastUpdBy != null">LAST_UPD_BY,</if>
            LAST_UPD_TS,
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            SYS_GUID(),
            <if test="title != null">#{title,jdbcType=VARCHAR},</if>
            <if test="content != null">#{content,jdbcType=VARCHAR},</if>
            <if test="noticeStatus != null">#{noticeStatus,jdbcType=VARCHAR},</if>
            <if test="createdBy != null">#{createdBy,jdbcType=VARCHAR},</if>
            systimestamp,
            <if test="lastUpdBy != null">#{lastUpdBy,jdbcType=VARCHAR},</if>
            systimestamp,
        </trim>
    </insert>

大家可以自行理解一下。

  • 21
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值