mybatis中的动态sql

1 mysql动态sql进行添加

<sql id="key">
    <trim suffixOverrides=",">
</if><if test="s1!= null"> s1, </if> 
<if test="s2!= null"> s2, </if> 
<if test="s3!= null"> s3, </if> 
<if test="s4!= null"> s4, </if> 
create_time 
<if test="s5!= null"> , s5, </if> 
    </trim>
</sql>

<sql id="value">
    <trim suffixOverrides=",">
 <if test="s1!= null"> #{s1}, </if>
 <if test="s2!= null"> #{s2}, </if>
 <if test="s3!= null"> #{s3}, </if>
 <if test="s4!= null"> #{s4}, </if>
 now()
<if test="s5!= null"> ,#{s5}, </if>

    </trim>
</sql>

<insert id="ADD">
    INSERT INTO table
    (<include refid="key"></include>)
    VALUES
    (<include refid="value"></include>)
</insert>

这条动态sql就可以解决掉你在不知道前台传过来的数据情况下,完成添加功能,也可以为其中某些不需要前台添加的代码设置默认值。

查询动态sql

<select id="query" parameterType="int" resultType="map">
SELECT * FROM table
    <where>
        <if test="s1!=null">
            s1= #{s1}
        </if>
    </where>
</select>

更新动态sql

<update id="update">
    UPDATE table
    <set>
        <trim prefixOverrides="," suffixOverrides=",">
       <if test="s1!= null"> s1= #{s1} , </if> 
       <if test="s2!= null"> s2= #{s2} , </if> 
       <if test="s3!= null"> s3= #{s3} , </if> 
        </trim>
    </set>
</update>

现在问题来了,别人那些又好看有漂亮的博客是怎么写的啊啊啊啊啊啊啊啊啊啊啊啊啊啊!

 

今天发现一个bug,就是我在写修改的动态sql的时候,出现了数据库语法错误,每次都会在前面后者和面多凭借一个and或者逗号之类的。

<update id="DeleteQualityInfo">
    UPDATE TB_CH_QUALITY  SET LOGIC_DELETE = 1
   <where>
        <if test="ch_quality_id != null">
            ch_quality_id = #{ch_quality_id}
        </if>
    </where>
</update>
<!--修改-->
<update id="update">
    UPDATE table
    <set>
        <trim suffixOverrides="," prefixOverrides=",">
        <if test="a!= null">
            a= #{a}
        </if>
        <if test="b!= null">
            , b= #{b}
        </if>
        <if test="c!= null">
            , c= #{c}
        </if>
        <if test="d!= null">
            , d= #{d}
        </if>
        <if test="e!= null">
            , e= #{e}
        </if>
        <if test="f!= null">
            , f= #{f}
        </if>
        <if test="g!= null">
            , g= #{g}
        </if>
        <if test="h!= null">
            , h= #{h}
        </if>
        </trim>
    </set>
</update>

在前面加上一个<trim></trim>在trim中设置两个属性,一个

suffixOverrides

,一个

prefixOverrides

这两个标签会删除你动态sql拼接时候多余出来的and或者逗号。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值