Mybatis动态SQL之UPDATE问题

在开发中,我们可能会根据需要对某条数据进行一处或者多处的修改,在MYSQL中,我们可以直接使用UPDATE 表名 SET 字段名=‘值’,如果我们在mybatis采用这种方法加if进行判断会好使吗?

先上SQL语句

    <update id="UserUpdateInfo">
        update user
        <set>
            <if test="username != null">username=#{username},</if>
            <if test="realName !=null">realName=#{realName},</if>
            <if test="nickname != null">nickname=#{nickname},</if>
            <if test="password != null">password=#{password},</if>
            <if test="className != null">className=#{className},</if>
            <if test="stuNum != null">stuNum#{stuNum},</if>
            <if test="department !=null">department=#{department},</if>
            <if test="email != null">email=#{email},</if>
            <if test="accountNonExpired != null">accountNonExpired=#{accountNonExpired},</if>
            <if test="accountNonLocked !=null">accountNonLocked=#{accountNonLocked},</if>
            <if test="credentialsNonExpired !=null"> credentialsNonExpired=#{credentialsNonExpired},</if>
            <if test="enabled != null">enabled=#{enabled}</if>
        </set>
            where id = #{id}
    </update>

那么这条的SQL语句的执行结果会怎样呢?我们先来试试看,从postman中的借口测试发现,报500。

 

打开控制台找报错的原因,发现如下:说不知道className列表

 但是此时,我们已经使用自动驼峰转下划线的方式,但是还是不成功。

遇到这种之后,我们该如何解决呢?

我们可以把sql语句作如下修改

    <update id="UserUpdateInfo">
        update user
            <trim prefix="set" suffixOverrides=",">
                <if test="username != null">username=#{username},</if>
                <if test="realName != null">real_name=#{realName},</if>
                <if test="nickname != null">nickname=#{nickname},</if>
                <if test="password != null">password=#{password},</if>
                <if test="className != null">class_name=#{className},</if>
                <if test="stuNum != null">stu_num#{stuNum},</if>
                <if test="department != null">department=#{department},</if>
                <if test="email != null">email=#{email},</if>
                <if test="accountNonExpired != null">account_non_expired=#{accountNonExpired},</if>
                <if test="accountNonLocked != null">account_non_nocked=#{accountNonLocked},</if>
                <if test="credentialsNonExpired != null"> credentials_non_xpired=#{credentialsNonExpired},</if>
                <if test="enabled != null">enabled=#{enabled}</if>
            </trim>
            where id = #{id}
    </update>

运行后的结果如下:

可以看到,成功解决了这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值