危险的 SQL

 

      看下这个 SQL , 有什么问题 ?

<update id="update" parameterType="CreativeGroupDO">
        update dsp_creative_group set gmt_modified = now()
        <if test="title != null">
            ,title = #{title,jdbcType=VARCHAR}
        </if>
        <if test="clickUrl != null">
            ,click_url = #{clickUrl,jdbcType=VARCHAR}
        </if>
        <where>
            <if test="creativeGroupId != null">
                and creative_group_id = #{creativeGroupId,jdbcType=BIGINT}
            </if>
        </where>
    </update>

        

      答案在下面已经用灰白色字体隐去。 请用鼠标滑过查看。

      咋看上去, 没啥问题;  可是, 如果 creativeGroupId = null 呢? 将会更新所有的 dsp_creative_group 记录的 title, clickUrl 为同一个值, 造成数据丢失。 你永远不知道应用程序会在什么时候将 creative_group_id 置为 null , 这几乎是不可控制的。  对于线上系统来说,一旦这样的事情发生, 绝对是灾难级的故障。 教训是: 永远、绝对不要在 update 的 where 字句中增加 if 条件!

 

posted @ 2015-03-10 21:01  琴水玉  阅读(443)  评论(0编辑  收藏  举报