首页 > 其他分享 >【mybtis】使用mybtis新增或更新空值问题

【mybtis】使用mybtis新增或更新空值问题

时间:2024-09-06 11:16:18浏览次数:5  
标签:mybtis 更新 空值 table null column1 id column3 column2

当使用#{}传递参数时,如果column1参数是null,mybatis会报错。

<update id="updateUser" parameterType="User">
    UPDATE user_table
    SET column1 = #{column1},
        column2 = #{column2},
        column3 = NULL
    WHERE id = #{id}
</update>

一般我们的做法是使用<if>标签过滤掉这个字段

<update id="updateUser" parameterType="User">
    UPDATE user_table
    <set>
        <if test="column1 != null">
            column1 = #{column1},
        </if>
        <if test="column2 != null">
            column2 = #{column2},
        </if>
    </set>
        column3 = NULL
    WHERE id = #{id}
</update>

但是如果有需求要将null值写进字段,那么上述方法就不行了。这时可以使用<choose>标签

<update id="updateUser" parameterType="User">
    UPDATE user_table
    <set>
        <choose>
            <when test="column1 != null">
                column1 = #{column1},
            </when>
            <otherwise>
                column1 = null,
            </otherwise>
        </choose>
        <choose>
            <when test="column2 != null">
                column1 = #{column2},
            </when>
            <otherwise>
                column2 = null,
            </otherwise>
        </choose>
    </set>
        column3 = NULL
    WHERE id = #{id}
</update>

这是更新的场景,如果是新增的时侯我们需要对某个字段写null进去,有种简单的方法不需要对每个字段进行判断,就是指定每个字段的jdbcType

<insert id="insert">
        insert into user_table (column1, column2, column3)
        values (#{column1, jdbcType=BIGINT}, #{column2, jdbcType=BIGINT}, #{column3,jdbcType=VARCHAR})
</insert>

具体类型的对照可以看这篇
本文来自博客园,作者:茄子_2008,转载请注明原文链接:https://www.cnblogs.com/xd502djj/p/10187158.html

标签:mybtis,更新,空值,table,null,column1,id,column3,column2
From: https://www.cnblogs.com/VergilYang/p/18399835

相关文章