1. 程式人生 > >mybatis填坑之一:關於mapper中逗號位置的寫法

mybatis填坑之一:關於mapper中逗號位置的寫法

  1. 寫法一
    <update id="updateRole" parameterType="com.coship.web.uc.dto.RoleParam">
            update t_role
            set 
            <if test="name != null and name !=''">
                name=#{name}
            </if>
            <if test="msg != null and msg !=''">
                ,msg=#{msg}
            </if>
            <if test="type != null and type !=''">
                ,type=#{type}
            </if>
            <if test="creator_id != null and creator_id !=''">
                ,creator_id=#{creator_id}
            </if>
            <if test="level != null and level !=''">
                ,level=#{level}
            </if>
            where id=#{id}
        </update>

     

  2. 寫法二
    <update id="updateRole" parameterType="com.coship.web.uc.dto.RoleParam">
            update t_role
            set 
            <if test="name != null and name !=''">
                name=#{name},
            </if>
            <if test="msg != null and msg !=''">
                msg=#{msg},
            </if>
            <if test="type != null and type !=''">
                type=#{type},
            </if>
            <if test="creator_id != null and creator_id !=''">
                creator_id=#{creator_id},
            </if>
            <if test="level != null and level !=''">
                level=#{level}
            </if>
            where id=#{id}
        </update>

    乍一看,握草,這他媽沒啥區別啊。但是仔細觀察後會發現,這兩個mapper的細微區別:逗號的位置不同,第一種寫法程式碼的健壯性比較強,而第二種寫法當我只傳部分屬性例如只傳name、msg、id這三個屬性的時候sql將變成:update t_role set name="武大郎",msg="賣燒餅,被西門大官人綠", where id="1"   此時報sql語法錯誤,而第一種寫法能巧妙避免該問題。